1.在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,配置如下:
@SpringBootApplication
@EnableRedisHttpSession
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.而@EnableRedisHttpSession这个注解是由弹簧会话数据redis的提供的,所以在pom.xml的文件中添加:
<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>
还有一个地方需要注意的pom.xml除了要添加以上依赖还需添加如下配置:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
3.接下来,则需要在application.properties中配置Redis的服务器的位置了,在这里,我们就用本机:
spring.redis.host=127.0.0.1
spring.redis.port=6379
这样以来,最简单的spring boot + redis实现session共享就完成了
如下是进行测试:
1.首先把的Tomcat的端口修改为8080
server.port=8080
2.新建Contrller
@RestController
@RequestMapping(value = "/admin/redis")
public class SessionController {
@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 ;
}
}
3.启动之后访问8080端口Tomcat:http://127.0.0.1:8080 / admin / redis/ first
{"request Url":"http://127.0.0.1:8080/admin/redis/first"}
4.接着,我们访问8080端口的会话:http://127.0.0.1:8080 / admin / redis/sessions
{"sessionId":"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed","message":null}
5.然后启动9090端口Tomcat:http://127.0.0.1:9090 / admin / redis / first
{“请求网址”:“http://127.0.0.1:9090/admin/redis/first”}
6.最后我们访问9090端口的会话:http://127.0.0.1:9090 / admin / redis / session
{"sessionId":"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed","message":null}
可见,8080与9090两个服务器返回结果一样,实现了会话的共享
其中问题:
启动项目的时候回出现
Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: java.net.UnknownHostException: 127.0.0.1
后面发现是spring.redis.host = 127.0.0.1 host后面多了两个空格各种找问题,去掉启动正常