spring @cacheable註解默認不支持方法級別的緩存失效時間,只能經過配置來配置全局的失效時間redis
若是須要實現對方法級別的緩存支持失效時間機制,有一種比較簡單的方法,spring配置文件以下:spring
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <context:component-scan base-package="redis.cache"/> <context:annotation-config/> <cache:annotation-driven cache-manager="redisCacheManager"/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:redis.properties</value> </list> </property> </bean> <!-- 配置JedisPoolConfig實例 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"/> <property name="maxTotal" value="${redis.maxActive}"/> <property name="maxWaitMillis" value="${redis.maxWait}"/> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!-- 配置JedisConnectionFactory --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"/> <property name="port" value="${redis.port}"/> <property name="password" value="${redis.pass}"/> <property name="database" value="${redis.dbIndex}"/> <property name="poolConfig" ref="poolConfig"/> </bean> <!-- 配置RedisTemplate --> <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"/> </bean> <!-- 配置RedisCacheManager --> <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg name="redisOperations" ref="redisTemplate"/> <property name="defaultExpiration" value="${redis.expiration}"/> <property name="expires"> <map> <entry key="test" value="30"/> </map> </property> </bean> </beans>
配置文件中的redisCacheManager對象配置了expires屬性,該屬性是一個map,能夠用來設置某些keys的過時時間緩存
defaultExpiration屬性設置了全局的默認失效時間,而expires屬性則根據map指定的key單獨設置失效時間,能夠指定多對key value,spa
時間單位爲:秒code
注意:expires屬性中map的key對應的是@cacheable註解中的value屬性指定的值,而不是key。例如:component
@Cacheable(value = "test", key = "'testUser_' + #id") public String testExpire(Long id) { return "test"; }
若是要爲上述方法設置過時時間30秒,則配置文件中expires屬性的key值必定要指定test,而不是testUser_#idxml