官方文檔,它是spring session項目的redis相關的一個子文檔:https://docs.spring.io/spring-session/docs/2.0.0.BUILD-SNAPSHOT/reference/html5/guides/boot-redis.htmlhtml
在spring boot的文檔中,告訴咱們添加@EnableRedisHttpSession來開啓spring session支持,配置以下:html5
@Configuration @EnableRedisHttpSession public class RedisSessionConfig { }
而@EnableRedisHttpSession這個註解是由spring-session-data-redis提供的,因此在pom.xml文件中添加:redis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
在配置文件application.properties裏配置spring sessionspring
spring.session.store-type=redis #指定redis實現spring session server.session.timeout=600 # Session 過時時間,單位s spring.session.redis.flush-mode= # Sessions 刷新模式 spring.session.redis.namespace= # Namespace for keys used to store sessions.
配置redis鏈接信息服務器
spring.redis.host=localhost spring.redis.password=secret spring.redis.port=6379
加上端口號session
server.port=8080
定義一個Controllerapp
@RestController @RequestMapping(value = "/admin/v1") public class QuickRun { @RequestMapping(value = "/first", method = RequestMethod.GET) public Map<String, Object> firstResp (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 = "/sessions", method = RequestMethod.GET) public Object sessions (HttpServletRequest request){ Map<String, Object> map = new HashMap<>(); map.put("sessionId", request.getSession().getId()); map.put("message", request.getSession().getAttribute("map")); return map; } }
複製上面的工程,把port改成9090ide
兩個項目都啓動好spring-boot
首先訪問8080端口的設置sessionpost
{"request Url":"http://localhost:8080/admin/v1/first"}
接着,咱們訪問8080端口的sessions,返回:
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
最後,再訪問9090端口的sessions,返回:
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}
可見,8080與9090兩個服務器返回結果同樣,實現了session的共享
若是此時再訪問9090端口的first的話,首先返回:
{"request Url":"http://localhost:9090/admin/v1/first"}
而兩個服務器的sessions都是返回:
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"}
這個時候打開redis客戶端,能夠查詢到session信息已經保存在redis裏。
注意點:
1.Redis版本要在2.8+