由於多臺服務器負載均衡,在獲取客戶端的sessionId的時候,會出現第一次和第二次不同,由於負載均衡的緣故,你的服務器最少兩臺,那麼客戶端鏈接第一次請求和第二次請求若是不是同一臺服務器的時候那麼sessionId就會變,爲了解決這個問題,我想到了session共享,若是兩臺服務器的session都存在redis上,那就不會有問題了java
第一步pom文件引入jia包web
<!--redis配置開始--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <!--redis配置結束-->
第二部配置文件配置redisredis
spring.redis.database=1 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.pool.max-active=20 spring.redis.pool.min-idle=20
第三步設置redissession配置spring
package com.hisun.framework; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.ConfigureRedisAction; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; //用戶session的生效時間是使用的這個單位是秒 @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 7 * 24 * 3600) public class RedisSessionConfig { @Bean public ConfigureRedisAction configureRedisAction() { //若是是本身搭建的redis或者阿里雲redis此處能夠沒有,由於開發了redis的config命令,可是亞馬遜的redis是不開發config命令的,必需要此段代碼 return ConfigureRedisAction.NO_OP; } }
這三部配置好就實現了session共享服務器
測試截圖session
測試controller代碼app
package com.hisun.test.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.hisun.framework.controller.CommonController; @RestController @RequestMapping("/${sys.name}") public class RoomController extends CommonController { @RequestMapping(value = "/web/testsession", method = RequestMethod.GET) public String testsession(HttpServletRequest request, HttpServletResponse response, HttpSession session) { String sss = session.getId(); return sss; } }