配置xml文件:spring自己提供 RedisCacheManager类,因为自己的需要可以自己实现这个类,也可以实例化spring的其它cacheManager类
<!-- redis pool相关配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 最小空闲数 -->
<property name="minIdle" value="${redis.minIdle}" />
<!-- 最大空闲数 -->
<property name="maxIdle" value="${redis.maxIdle}" />
<!-- 最大连接数 -->
<property name="maxTotal" value="${redis.maxTotal}" />
<!-- 最大等待时间 单位毫秒(ms) -->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<!-- 使用连接时测试连接是否可用 -->
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- jedis客户端连接工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="poolConfig" ref="poolConfig" />
<property name="database" value="${redis.database}" />
<property name="port" value="${redis.port}" />
<property name="hostName" value="${redis.host}" />
<property name="password" value="${redis.password}" />
</bean>
<!-- redisTemplate模板 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
<!-- redis缓存管理器 -->
<bean id="cacheManager" class="org.gyy.redis.spring_redis.RedisCacheManager">
<constructor-arg name="redisOperations" ref="redisTemplate" />
<!-- 是否事务提交,如果事务回滚,缓存也回滚,默认false -->
<property name="transactionAware" value="true" />
<!-- 设置缓存超时时间 已实现自动续期 如果不设置将永久存在 -->
<property name="expires">
<map>
<!-- 模块信息相关缓存配置 -->
<entry key="cache_module" value="1800" />
</map>
</property>
</bean>
<!-- 支持缓存注解 -->
<cache:annotation-driven cache-manager="cacheManager" />
properties文件:
###Redis缓存配置
#缓存池最小空闲数
redis.minIdle=5
#缓存池最大空闲数
redis.maxIdle=100
#缓存池最大连接数
redis.maxTotal=300
#最大等待时间
redis.maxWaitMillis=3000
#使用连接时是否测试可用
redis.testOnBorrow=true
#主机地址
redis.host=
#主机端口
redis.port=6379
#主机密码
redis.password=
#数据库下标
redis.database=4
spring提供了很方便的注解缓存的方法,只需要在方法上面注解就可以自动使用缓存,不需要自己手动去操作,这里有一个小坑,注解缓存时key最好不要用integer类型,
因为你手动去获取的时候key支持是string类型,就会拿不到,