Spring之@EnableRedisHttpSession註解

在集羣系統中,經常會需要將Session進行共享。不然會出現這樣一個問題:用戶在系統A上登陸以後,假如後續的一些操作被負載均衡到系統B上面,系統B發現本機上沒有這個用戶的Session,會強制讓用戶重新登陸。此時用戶會很疑惑,自己明明登陸過了,爲什麼還要自己重新登陸。

分佈式Session的解決方案

  • 使用cookie來完成(很明顯這種不安全的操作並不可靠)
  • 使用Nginx中的ip綁定策略,同一個ip只能在指定的同一個機器訪問(不支持負載均衡)
  • 利用數據庫同步session(效率不高)
  • 使用tomcat內置的session同步(同步可能會產生延遲)
  • 使用token代替session
  • 我們使用spring-session以及集成好的解決方案,存放在Redis中

最後一種方案是本文要介紹的重點。

EnableRedisHttpSession使用

添加依賴

<!-- spring session的依賴 -->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>

添加註解 @EnableRedisHttpSession

/**
 * session託管到redis
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 3600*24, redisFlushMode = RedisFlushMode.ON_SAVE, redisNamespace = "aurora-web")
public class RedisSessionConfig {
	
}

maxInactiveIntervalInSeconds: 設置 Session 失效時間,使用 Redis Session 之後,原 Spring Boot 的 server.session.timeout 屬性不再生效。

經過上面的配置後,Session調用就會自動去Redis存取。另外,想要達到Session共享的目的,只需要在其他的系統上做同樣的配置即可。

@EnableRedisHttpSession源碼

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({RedisHttpSessionConfiguration.class})
@Configuration
public @interface EnableRedisHttpSession {
    //Session默認過期時間,單位秒,默認1800秒
    int maxInactiveIntervalInSeconds() default 1800;

    //配置key的namespace,默認的是spring:session,如果不同的應用共用一個redis,應該爲應用配置不同的namespace,這樣才能區分這個Session是來自哪個應用的
    String redisNamespace() default "spring:session";

    //配置刷新Redis中Session方式,默認是ON_SAVE模式,只有當Response提交後纔會將Session提交到Redis,也可以配置成IMMEDIATE模式,即所有對Session的更改會立即更新到Redis
    RedisFlushMode redisFlushMode() default RedisFlushMode.ON_SAVE;

    //清理過期Session的定時任務
    String cleanupCron() default "0 * * * * *";
}

其中,@Import({RedisHttpSessionConfiguration.class})  這個註解的主要作用是註冊一個SessionRepositoryFilter,這個Filter會攔截到所有的請求,對Session進行操作,具體的操作細節會在後面講解,這邊主要了解這個註解的作用是註冊SessionRepositoryFilter就行了。注入SessionRepositoryFilter的代碼在RedisHttpSessionConfiguration這個類中。

@Configuration
@EnableScheduling
public class RedisHttpSessionConfiguration extends SpringHttpSessionConfiguration implements BeanClassLoaderAware, EmbeddedValueResolverAware, ImportAware, SchedulingConfigurer {
      ......
}

 

參考:Spring系列.@EnableRedisHttpSession原理簡析

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章