經過spring session,結合redis,能夠把session信息存儲在redis中,實現多個服務間的session共享。java
如下介紹在springboot工程中如何使用spring sessionredis
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、在配置類中開啓對RedisHttpSession的支持spring
在配置類加註解@EnableRedisHttpSession
springboot
server: port: 8080 spring: redis: host: localhost port: 6379 jedis: pool: max-idle: 10 max-active: 8 max-wait: -1 min-idle: 0
接下來對session的使用和未使用spring session前一致。session
@RestController public class LogInController { @GetMapping("/login") public String login(@RequestParam("username") String username, HttpServletRequest request){ HttpSession session = request.getSession(true); session.setAttribute("username",username); return username+",login success"; } @GetMapping("/logout") public String logout(HttpServletRequest request){ HttpSession session = request.getSession(true); Object username = session.getAttribute("username"); session.invalidate(); return username+",logout success"; } @GetMapping("/index") public String sayHello(HttpServletRequest request){ HttpSession session = request.getSession(false); System.out.println(session); if(session==null){ return "未登陸"; } Object username = session.getAttribute("username"); return username+",welcome"; } }
將當前工程複製一份,改變端口爲8082,在工程一中訪問/login進行登陸,啓動工程2,在工程2中訪問/index能夠獲取到登陸信息,兩個服務間實現了session共享。app
注意這裏的session共享是在同一個域名下的多個服務間進行的。spring-boot