您的位置:首页 > 数据库 > Redis

redis实现分布式集群环境session共享(代码示例与验证)

2019-02-27 21:37 811 查看

1、redis实现分布式集群环境session共享的好处

可以实现多机器部署同一套服务(代码),性能更好,可承受更高的用户并发

2、如何使用

1)思路是利用cookie保存sessionId

2)   配置过程

  • 在pom文件添加依赖
[code]<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
  • 在配置文件中开启redis session 缓存@EnableRedisHttpSession,并指定缓存的时间maxInactiveIntervalInSeconds

  • 编写测试代码
[code]
@RestController
public class SessionController {

@RequestMapping(value = "/setSession", method = RequestMethod.GET)
public Map<String, Object> setSession (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 = "/getSession", method = RequestMethod.GET)
public Object getSession (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("sessionIdUrl",request.getSession().getAttribute("request Url"));
map.put("sessionId", request.getSession().getId());
return map;
}
}

3、测试

由于我们是利用cookie来存储sessionid,所以我们可以在谷歌浏览器中打开隐身模式清空cookie来验证缓存的时间

1)首先我们要启动redis服务(如果是Windows用户,可参考我的命令,其中主要启动命令是redis-server.exe redis.windows.conf)

2)连接redis(可参考我的命令)

3)在隐身窗口中分别输入localhost:8080/setSession;输入localhost:8080/getSession获得sessionid

4)在redis中输入命令keys *   

5)输入ttl (并复制带expires的sessionid上图中箭头处)

可看到过期时间

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: