ZBLOG

Spring Cache + EHcache + MemoryCache 怎么实现注解自定义过期时间

  1. 首先,需要在Spring配置文件中配置CacheManager和Cache的相关信息,如下所示:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehCacheManager"/>
</bean>

<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
</bean>

<bean id="memoryCache" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
    <property name="name" value="memoryCache"/>
</bean>

其中,cacheManager定义了使用EHCache作为缓存,而memoryCache则定义了使用ConcurrentMap作为缓存。

  1. 然后,在需要使用缓存的方法上添加@Cacheable注解,并指定缓存名称和key,如下所示:
@Cacheable(value = "memoryCache", key = "#id")
public User getUserById(Long id) {
    // ...
}
  1. 最后,在ehcache.xml中配置缓存过期时间,如下所示:
<cache name="memoryCache" maxEntriesLocalHeap="1000" timeToLiveSeconds="3600"/>

其中,timeToLiveSeconds表示缓存的过期时间,单位为秒。

这样,就可以实现注解自定义过期时间的功能了。如果需要对不同的缓存设置不同的过期时间,只需在ehcache.xml中分别设置即可。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1755

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?