Redis实现分布式集群环境session共享

多机器部署同一套服务(代码),性能更好,能承受更高的用户并发

当一个用户发送请求到第一台机器,内存存储sessioni的话,剩余的99台每次还需要存储

Cookie与Session

Cookie: Cookie 是一小段文本信息,伴随着用户请求和页面在 Web 服务器和浏览器之间传递。Cookie 包含每次用户访问站点时 Web 应用程序都可以读取的信息,我们可以看到在服务器写的cookie,会通过响应头Set-Cookie的方式写入到浏览器

HTTP协议是无状态的,并非TCP一样进行三次握手,对于一个浏览器发出的多次请求,WEB服务器无法区分是不是来源于同一个浏览器。所以服务器为了区分这个过程会通过一个 sessionid来区分请求,而这个sessionid是怎么发送给服务端的呢。cookie相对用户是不可见的,用来保存这个sessionid是最好不过了

Redis实现分布式集群配置过程

1)引入依赖

		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
		</dependency>

2)开启注解 redis session缓存

设置过期时间50s

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 50)

测试

@RestController
public class SessionController {

    @RequestMapping(value = "/setSession", method = RequestMethod.GET)
    public Map<String, Object> setSession (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        request.getSession().setAttribute("request Url", request.getRequestURL());
        map.put("request Url", request.getRequestURL());
        return map;
    }

    @RequestMapping(value = "/getSession", method = RequestMethod.GET)
    public Object getSession (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("sessionIdUrl",request.getSession().getAttribute("request Url"));
        map.put("sessionId", request.getSession().getId());
        return map;
    }
}

SpringBoot会存在两个Sessionid 带有expirations是第一个设置的 第二个有180s的过期时间,可以在第一个过期时间再次赋值时间
在这里插入图片描述
验证过程

打开隐身模式清空cookie来验证缓存的时间

猜你喜欢

转载自blog.csdn.net/q736317048/article/details/113854231
今日推荐