1.在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,配置如下:
@SpringBootApplication
@EnableRedisHttpSession
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,所以在pom.xml文件中添加:
org.springframework.boot
spring-boot-starter-redis
org.springframework.session
spring-session-data-redis
还有一个地方需要注意Pom.xml除了要添加以上依赖还需添加如下配置:
redis.clients
jedis
2.9.0
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 firstResp(HttpServletRequest request){
Map 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 map = new HashMap<>();
map.put("sessionId" ,request.getSession().getId());
map.put("message" , request.getSession().getAttribute("map"));
return map ;
}
}
{"request Url":"http://127.0.0.1:8080/admin/redis/first"}
{"sessionId":"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed","message":null}
{"request Url":"http://127.0.0.1:9090/admin/redis/first"}
{"sessionId":"9ff88ad6-90fa-49aa-86a3-a3c8fc155eed","message":null}
可见,8080与9090两个服务器返回结果一样,实现了session的共享
其中问题:
启动项目的时候回出现
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 后面多了两个空格 各种找问题,去掉启动正常