在之前的小结Redis分布式实现(原生实现)中实现了原生的分布式redis缓存方案,但它的侵入性太强,对于已有的项目改造起来成本较大。今天就来通过Spring Session来实现无侵入性方案。
pom中导入需要的依赖:
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>2.9.0</version>
</dependency>
web.xml中添加filter,这样当请求.do接口时httpsesion就会转化成我们需要的redissession:
<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>*.do</url-pattern>
</filter-mapping>
新建applicationContext-spring-session.xml用于对jedis的工厂、链接池设置(只列出基本的设置,详细需要进入代码查看):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="1800"/>
</bean>
<bean id="defaultCookieSerializer" class="org.springframework.session.web.http.DefaultCookieSerializer">
<property name="domainName" value=".happymmall.com"/>
<property name="useHttpOnlyCookie" value="true"/>
<property name="cookiePath" value="/"/>
<property name="cookieMaxAge" value="31536000"/>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="20"/>
</bean>
<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="poolConfig" ref="jedisPoolConfig"/>
</bean>
</beans>
最后将需要缓存的bean实现Serializable(否者redis无法写入)
开始调用接口测试:
这里看到通过在wen.xml文件的设置session已经被转化成redissession,并设置了创建时间等:
通过redis可视化工具看到需要被存储等bean已经被存入,并且还添加了expires等关联。当关联时间到期时会被清除,缓存的bean不会,它会到自己过期才清除。但由于关联过期,缓存也自然无法获取。