1. 程式人生 > >使用spring-session redis共享session

使用spring-session redis共享session

原因

  • 之前有一篇分享過session共享的方案,redis共享session確實有很多好處,但是在原有的工程上面新增去修改session放到redis裡面去,確實有一定的改動量。但是我們可以通過spring提供的spring-session和redis做到無感切換session。原理是spring做了一層攔截器,對Session做了一層封裝,當我們進行呼叫session.setAttribute()的時候,其實在進入spring封裝好的方法中,存放到redis中去了。

spring boot 配置

  • maven 新增

    <dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    </dependency>
  • properties配置
# Session store type
spring.session.store-type=redis
# Session timeout. If a duration suffix is not specified, seconds will be used. session過期時間
server.servlet.session.timeout=3600
# Sessions flush mode.
spring.session.redis.flush-mode=on-save
# Namespace for keys used to store sessions.
spring.session.redis.namespace=spring:session
  • 開啟RedisHttpSession

    @EnableRedisHttpSession

    就差不多了。。