springboot配置基於redis的session

springboot配置基於redis的session

  • 爲什麼要使用session共享?

    因爲在多個服務器之間我準確認識同一客戶端,以方便保存會話狀態。

  • 只有redis這一種方案嗎?或者說基於redis的Session能有什麼優勢?

    不是的,我們的目的是要讓會話狀態得以保存和準確識別,比如nginx基於hash來進行輪詢,那每次會話都會到同樣一臺服務上,也可以保證會話狀態。

    而且,本質是我們把會話狀態放入nosql數據庫,每次從數據庫中讀取還原。基於redis方案比較成熟還有就是redis內存操作等其它優勢,可以去redis官網瞭解。

通過redis來實現Session共享

  1. 引入必要的pom依賴

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    
  2. 編寫必要的配置信息

      # redis 配置
    spring:  
      redis:
        database: 0
        cluster:
          max-redirects: 3
          nodes:
            - 192.168.15.208:7001
            - 192.168.15.208:7002
            - 192.168.15.208:7003
            - 192.168.15.208:7004
            - 192.168.15.208:7005
            - 192.168.15.208:7006
    
        #password: 1234
        lettuce:
          pool:
            max-active: 1000
            max-wait: -1
            max-idle: 10
            min-idle: 5
        timeout: 3000
      data:
        redis:
          repositories:
            enabled: false
    
    
  3. 啓動基於redis的session共享,在啓動類上添加@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)

    
    @SpringBootApplication
    @EnableCaching
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
    public class SaleWhiteBoardApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SaleWhiteBoardApplication.class, args);
        }
    
    }
    
    

    maxInactiveIntervalInSeconds: 設置 Session 失效時間,使用 Spring Session 之後,原 Spring Boot 配置文件 application.yml 中的 server.session.timeout 屬性不再生效

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