在已经引入redis的项目中实现session共享很简单,方法如下:

1、加入maven配置

<!-- redis共享session -->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

2、增加application.yml配置

spring:
  session:
    store-type: redis #设置session存储类型为redis

3、使用controller验证下

@Slf4j
@RestController
@RequestMapping("redis")
public class RedisDemoController {
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "/setRedis", method = RequestMethod.POST)
    public String setRedis(String value, HttpServletRequest httpServletRequest) {
        String result;
        try {
            redisUtil.setValue("redis_key", value);
            httpServletRequest.getSession().setAttribute("my_redis_session", value);
            result = "redis设置成功";
        } catch (Exception e) {
            result = "redis设置失败:" + e.getMessage();
        }
        return result;
    }


    @RequestMapping(value = "/getRedis", method = RequestMethod.GET)
    public String getRedis(HttpServletRequest httpServletRequest) {
        String result;
        try {
            String value = (String) redisUtil.getValue("redis_key");
            result = "redis读取成功:" + value;
            String myRedisSession = (String) httpServletRequest.getSession().getAttribute("my_redis_session");
            System.out.println(myRedisSession);
        } catch (Exception e) {
            result = "redis读取失败:" + e.getMessage();
        }
        return result;
    }
}

4、查看结果

5、这样,无论你用的是原生的httpServletRequest.getSession()获取的session,还是在shiro中从SecurityUtils.getSubject().getSession()里获取的session,redis都能替你进行管理了。

有什么不清楚的可以参考github上的demo的redisClusterSession分支:

https://github.com/whol/springbootdemo

最后修改于 2019-03-07 11:36:45
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇