java web項目,不依賴於web容器,實現負載平衡,必須解決session共用問題。網上解決方案有很多,但是我覺得使用 spring-session +redis是最方面快捷的,不用重複造輪子,且不用修改項目的代碼,並且使項目使用的session與web容器解耦, 完全由容器的httpsession轉為使用spring提供的session. 具體怎麼使用,請訪問 spring的官方網站。 這裡寫下我的項目中使用spring session+redis的步驟。 項目使用的是maven結構的web項目 1.pom.xml
<!-- spring-session begin--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.7.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>1.3.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version><scope>compile</scope></dependency> <!-- spring-session end-->
注意:剛開始我的spring架構套件(就是好多spring的包)用的是4.0的,但是啟動tomcat伺服器的時候報錯,說不能初始化redisTemplate,跑去stackofflow上看,有說是因為jar的問題,需要升級spring架構必須高於4.2.1,因為redistemplate換了構造器。於是將spring架構升到4.3.7.RELEASE。就ok了。 2.配置filter 在web.xml中,加上這段配置 必須位於filter鏈的最前面
<!-- spring-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>
3.在applicationContext.xml(這是我的spring容器設定檔的名字)中註冊需要的bean。(用註解也行,但我是用的xml配置)
<!-- redis --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="localhost" /> <property name="port" value="6379" /> <property name="password" value="****"/> <property name="usePool" value="true"/> <property name="poolConfig" ref="jedisPoolConfig"/> </bean> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> </bean> <!-- 將session放入redis --> <bean id="redisHttpSessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <property name="maxInactiveIntervalInSeconds" value="1800"/> </bean>
OK,到這兒就結束了,系統中的代碼一點也不用改動。這真的解耦啊,spring這的非常強大。