SpringBoot2.X使用Redis实现Session共享
一、为什么要进行Session共享
Session是服务器用来保存用户操作的一系列会话信息,由Web容器进行管理。单机情况下,不存在Session共享的情况,分布式情况下,如果不进行Session共享会出现请求落到不同机器要重复登录的情况。Session共享也有很多种实现方式,可以自行百度。
二、SpringBoot2.X如何实现Session共享
1、因为依赖JAR包,POM文件配置如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>2.3.3.RELEASE</version> </dependency>
2、修改YML配置文件,最好保证redis支持sentinel和单机模式配置如下:
spring: session: store-type: redis redis: # sentinel: # master: redis-cluster # nodes: test.sentinel2.imfbp.com:26379,test.sentinel3.imfbp.com:26379 timeout: 5000 jedis: pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0 database: 2 host: 10.10.4.158 port: 6383
3、登录时往Session中写入关键信息,比如用户名编码和用户ID,如下:
request.getSession().setAttribute(LoginEnum.LONGIN_USER_CODE.getloginInfo(), username); request.getSession().setAttribute(LoginEnum.LONGIN_USER_ID.getloginInfo(), bossUser.getId());
4、登出时清空Session中的关键信息,比如用户名编码和ID,如下:
request.getSession().removeAttribute(LoginEnum.LONGIN_USER_CODE.getloginInfo()); request.getSession().removeAttribute(LoginEnum.LONGIN_USER_ID.getloginInfo());
5、实现HandlerInterceptor接口,进行相关需要的控制,比如权限控制,关键代码:
String userCode = (String) session.getAttribute(LoginEnum.LONGIN_USER_CODE.getloginInfo()); String ajax = request.getHeader("X-Requested-With"); if (StringUtils.isBlank(userCode)) { if ("XMLHttpRequest".equals(ajax)) { response.setHeader("ajaxUrl", redirertUrl); response.getWriter().write(redirertUrl); } else { response.sendRedirect(redirertUrl); } return false; } Map<String, List<Toolbar>> permitMap = getPermitModule(request.getSession()); if (permitMap == null || permitMap.keySet() == null || permitMap.keySet().size() == 0 || StringUtils.isBlank(userCode)) { setPermit(request); request.setAttribute("LOGIN_STATE", LoginEnum.LOGIN_STATE); } setInvocationInfo(request);
6、在启动类中增加注解:
@SpringBootApplication( exclude = { RedisAutoConfiguration.class, RedisRepositoriesAutoConfiguration.class })
二、如何验证?
1、配置两个不同的应用启动, 注意激活不同的配置文件,配置文件里面的端口使用不同的端口。
2、访问系统,或者访问不同的接口后,查看redis存储中的SessionID,如下图,sessionID始终为一个,而且不会跳转到登录页面