我可以为@Cacheable设置TTL吗?

Pio*_*otr 87 java spring

我正在尝试@CacheableSpring 3.1 的注释支持,并想知道是否有任何方法可以通过设置TTL使缓存数据在一段时间后清除?现在我可以看到我需要通过使用它来清除它@CacheEvict,并且通过使用它@Scheduled我可以自己做一个TTL实现但是对于这么简单的任务似乎有点多了?

小智 52

Spring 3.1和Guava 1.13.1:

@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {

    @Override
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {

            @Override
            protected Cache createConcurrentMapCache(final String name) {
                return new ConcurrentMapCache(name,
                    CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
            }
        };

        return cacheManager;
    }

    @Override
    public KeyGenerator keyGenerator() {
        return new DefaultKeyGenerator();
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 对于Spring 4.1,扩展CachingConfigurerSupport并仅覆盖cacheManager(). (17认同)
  • @JohannesFlügel 为什么不发布任何示例代码? (4认同)

JB *_*zet 38

请参阅http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#cache-specific-config:

如何设置TTL/TTI /逐出政策/ XXX功能?

直接通过缓存提供程序.缓存抽象是......好吧,抽象不是缓存实现

因此,如果您使用EHCache,请使用EHCache的配置来配置TTL.

您还可以使用Guava的CacheBuilder构建缓存,并将此缓存的ConcurrentMap视图传递给ConcurrentMapCacheFactoryBean的setStore方法.


ana*_*ocs 33

以下是在Spring中设置Guava Cache的完整示例.我使用Guava而不是Ehcache,因为它的重量有点轻,配置似乎更直接.

导入Maven依赖项

将这些依赖项添加到您的maven pom文件并运行clean和packages.这些文件是用于CacheBuilder的Guava dep和Spring辅助方法.

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

配置缓存

您需要创建一个CacheConfig文件以使用Java配置来配置缓存.

@Configuration
@EnableCaching
public class CacheConfig {

   public final static String CACHE_ONE = "cacheOne";
   public final static String CACHE_TWO = "cacheTwo";

   @Bean
   public Cache cacheOne() {
      return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.MINUTES)
            .build());
   }

   @Bean
   public Cache cacheTwo() {
      return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .build());
   }
}
Run Code Online (Sandbox Code Playgroud)

注释要缓存的方法

添加@Cacheable注释并传入缓存名称.

@Service
public class CachedService extends WebServiceGatewaySupport implements CachedService {

    @Inject
    private RestTemplate restTemplate;


    @Cacheable(CacheConfig.CACHE_ONE)
    public String getCached() {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> reqEntity = new HttpEntity<>("url", headers);

        ResponseEntity<String> response;

        String url = "url";
        response = restTemplate.exchange(
                url,
                HttpMethod.GET, reqEntity, String.class);

        return response.getBody();
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到一个更完整的例子,带有带注释的截图: Spring中的Guava Cache

  • 注意:Guava 缓存现在在 Spring 5 中被弃用 (/sf/ask/3092255981/) (3认同)

Atu*_*tum 26

我使用像这样的生活黑客

@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
    public static final String GAMES = "GAMES";
    @Bean
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);

        return cacheManager;
    }

@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 ,  initialDelay = 500)
public void reportCacheEvict() {
    System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
Run Code Online (Sandbox Code Playgroud)

  • 按计划清除整个缓存可能是让事情正常运行的一个方便的技巧,但此方法不能用于为项目提供 TTL。即使是*condition*值也只能声明是否删除整个缓存。其背后的事实是 ConcurrentMapCache 存储没有任何时间戳的对象,因此无法按原样评估 TTL。 (8认同)

jo8*_*937 26

Springboot 1.3.8

import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.cache.CacheBuilder;

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

@Override
@Bean
public CacheManager cacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    return cacheManager;
}

@Bean
public CacheManager timeoutCacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(5, TimeUnit.SECONDS);
    cacheManager.setCacheBuilder(cacheBuilder);
    return cacheManager;
}

}
Run Code Online (Sandbox Code Playgroud)

@Cacheable(value="A", cacheManager="timeoutCacheManager")
public Object getA(){
...
}
Run Code Online (Sandbox Code Playgroud)


Ham*_*eji 8

使用 Redis 时,可以在属性文件中设置 TTL,如下所示:

spring.cache.redis.time-to-live=1d # 1 day

spring.cache.redis.time-to-live=5m # 5 minutes

spring.cache.redis.time-to-live=10s # 10 seconds


Ale*_*ech 6

对我来说最简单的方法是使用咖啡因缓存,它可以直接在application.yml文件中配置。

您可以通过参数设置TTL expireAfterWrite。示例配置如下:

spring:
  cache:
    caffeine:
      spec: expireAfterWrite=15m
    cache-names: mycache
Run Code Online (Sandbox Code Playgroud)

这将在 15 分钟后驱逐元素。

  • 这是逐出“mychace”中的所有缓存数据还是仅逐出 1500 万年前写入的项目? (3认同)

luk*_*s77 5

这可以通过扩展org.springframework.cache.interceptor.CacheInterceptor并覆盖“ doPut”方法来完成-org.springframework.cache.interceptor.AbstractCacheInvoker您的替代逻辑应使用知道为缓存条目设置TTL的缓存提供程序put方法。 (在我的情况下,我使用HazelcastCacheManager)

@Autowired
@Qualifier(value = "cacheManager")
private CacheManager hazelcastCacheManager;

@Override
protected void doPut(Cache cache, Object key, Object result) {
        //super.doPut(cache, key, result); 
        HazelcastCacheManager hazelcastCacheManager = (HazelcastCacheManager) this.hazelcastCacheManager;
        HazelcastInstance hazelcastInstance = hazelcastCacheManager.getHazelcastInstance();
        IMap<Object, Object> map = hazelcastInstance.getMap("CacheName");
        //set time to leave 18000 secondes
        map.put(key, result, 18000, TimeUnit.SECONDS);



}
Run Code Online (Sandbox Code Playgroud)

在缓存配置中,您需要添加这两个bean方法,以创建自定义拦截器实例。

@Bean
public CacheOperationSource cacheOperationSource() {
    return new AnnotationCacheOperationSource();
}


@Primary
@Bean
public CacheInterceptor cacheInterceptor() {
    CacheInterceptor interceptor = new MyCustomCacheInterceptor();
    interceptor.setCacheOperationSources(cacheOperationSource());    
    return interceptor;
}
Run Code Online (Sandbox Code Playgroud)

当您要在条目级别而不是在缓存级别全局设置TTL时,此解决方案非常有用