使用SpringSession和Redis解決分布式Session共享問題


SpringSession優勢

  • 遵循servlet規范,同樣方式獲取session,對應用代碼無侵入且對於developers透明化

關鍵點在於做到透明和兼容

  • 接口適配:仍然使用HttpServletRequest獲取session,獲取到的session仍然是HttpSession類型——適配器模式
  • 類型包裝增強:Session不能存儲在web容器內,要外化存儲——裝飾模式

基本環境需求

進行使用Spring Session的話,首先的是已經安裝好的有一個 Redis服務器!

添加項目依賴(最基本的依賴使用)

<!--Spring Session-->
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>1.3.0.RELEASE</version>
    <type>pom</type>
</dependency>

(3)添加Spring配置文件

添加了必要的依賴之后,我們需要創建相應的Spring配置。Spring配置是要創建一個Servlet過濾器,它用Spring Session支持的HttpSession實現來替換容器本身HttpSession實現。這一步也是Spring Session的核心。

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>

<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  <property name="hostName" value="127.0.0.1"/>
  <property name="port" value="6379"/>
  <property name="password" value=""/>
</bean>

在web.xml中添加DelegatingFilterProxy(一定要放在自定義filter之前,不然會出現自定義filter中無法獲取到session的問題)

<filter>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSessionRepositoryFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>ERROR</dispatcher>
</filter-mapping>

DelegatingFilterProxy將通過springSessionRepositoryFilter的名稱查找Bean並將其轉換為過濾器。對於調用DelegatingFilterProxy的每個請求,也將調用springSessionRepositoryFilter。

使用工具查看Redis內容:

對於分布式環境Session跨域共享的問題,不管是使用開源的框架還是使用自己開發的框架,都需要明白的一個問題是:在Tomcat容器中創建Session是一個很耗費內存的事情。因此,我們在自己寫類似框架的時候,我們一定要注意的是,並不是Tomcat為我們創建好了Session之后,我們首先獲取Session然后再上傳到Redis等進行存儲,而是直接有我們自己創建Session,這一點是至關重要的!

 

關於Error creating bean with name ‘enableRedisKeyspaceNotificationsInitializer’錯誤的處理:

添加如下配置讓Spring Session不再執行config命令

<util:constant static-field="org.springframework.session.data.redis.config.ConfigureRedisAction.NO_OP"/>

如果不添加的話,會報如下錯誤:

Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/session/data/redis/config/annotation/web/http/RedisHttpSessionConfiguration.class]:
Invocation of init method failed; nested exception is java.lang.IllegalStateException: Unable to configure Redis to keyspace notifications.
See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent
Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR unknown command config


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM