简体   繁体   English

如何在Amazon AWS Elasticache Redis + Spring Data上配置驱逐(生存时间)

[英]How to configure eviction (time to live) on Amazon AWS Elasticache Redis + Spring Data

I'm working on a project where we use Spring Data Cache abstraction along with AWS Elasticache Redis and I would like to know how to configure the eviction time of the objects on the cache. 我正在开发一个项目,我们使用Spring Data Cache抽象和AWS Elasticache Redis,我想知道如何配置缓存上对象的逐出时间。

There's not too much official documentation on how to configure Spring Data Cache Abstraction with Elasticache Redis. 关于如何使用Elasticache Redis配置Spring Data Cache Abstraction的官方文档并不多。 We found some good info here: http://blog.joshuawhite.com/java/caching-with-spring-data-redis/ 我们在这里找到了一些很好的信息: http//blog.joshuawhite.com/java/caching-with-spring-data-redis/

But there's nothing about configuring eviction time or time to live of the objects that are cached. 但是,没有任何关于配置被驱逐对象的驱逐时间或时间。 Any help? 有帮助吗?

You can configure eviction time by providing expires map in RedisCacheManager. 您可以通过在RedisCacheManager中提供过期映射来配置驱逐时间。 For example you have cacheable method specified like that: 例如,您具有如下指定的可缓存方法:

@Cacheable(value = "customerCache", key = "#id")
public Customer findOne(Integer id) {
    return customerRepository.findOne(id);
}

in your applicationContext.xml it will look like this: 在您的applicationContext.xml中,它将如下所示:

<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager" c:template-ref="redisTemplate" p:usePrefix="true">
    <property name="expires">
        <map>
            <entry key="customerCache" value="350"/>                    
        </map>
    </property>
</bean>

This will configure "customerCache" values to be evicted 350 seconds after these were first added to the cache. 这将配置“customerCache”值在首次添加到缓存后350秒被驱逐。

In addition to the accepted answer, you can also configure the cache via Java config. 除了接受的答案,您还可以通过Java配置配置缓存。 This Spring Cloud Sample was helpful to me. 这个Spring Cloud Sample对我有帮助。 This was adapted from ReferenceApplication.java in that project. 这是从该项目中的ReferenceApplication.java改编而来的。

In your @Configuration section, you can say this: @Configuration部分中,您可以这样说:

@Configuration
@EnableElastiCache({@CacheClusterConfig(name = "customerCache", expiration = 360)})
@Profile("!local")
protected static class ElastiCacheConfiguration {}

It has the added benefit of using Spring Profiles . 它具有使用Spring Profiles的额外好处。 The cluster is picked up from your aws-config.xml . aws-config.xml获取集群。 It is really important to set the region context in the xml config or your cluster won't be picked up. 在xml配置中设置区域上下文非常重要,否则您的群集将不会被选中。

<aws-context:context-region region="<your-region-here" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM