spring boot + redis 实现session共享
- - 编程语言 - ITeye博客这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,配置如下:. 而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,所以在pom.xml文件中添加:
.
其工作原理,可简单用图描述(假设服务A运行有有个多个实例):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
spring.redis.database=1
spring.redis.host=localhost
spring.redis.password=xxxxx
spring.redis.port=6379
# server.port=8080
server.port=8081
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
}
package com.example.demo.controller;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
@RequestMapping(value = "/")
public class Hello {
@RequestMapping(value = "/set", method = RequestMethod.GET)
public Map<String, Object> firstResp (HttpServletRequest request){
request.getSession().setAttribute("testKey", "testValue");
Map<String, Object> map = new HashMap<>();
map.put("testKey", "testValue");
return map;
}
@RequestMapping(value = "/query", method = RequestMethod.GET)
public Object sessions (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("sessionId", request.getSession().getId());
map.put("testKey", request.getSession().getAttribute("testKey"));
return map;
}
}
浏览器访问测试
http://127.0.0.1:8080/set
, 127.0.0.1:8081/query
接口,效果如下: 可以看出两个独立的应用已经共享了同一个session。