sunmingtao / sample-code

3 stars 4 forks source link

How to create a cache in Spring with TTL? #163

Closed sunmingtao closed 4 years ago

sunmingtao commented 4 years ago

Spring 5+

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.4.1</version>
  </dependency>
  <dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.8.8</version>
  </dependency>
</dependencies>

Spring bean config

@Configuration
@EnableCaching
public class CacheConfig {

    private final long allocatedToListExpireInDays;

    public CacheConfig(
            @Value("${banjo.job.allocated.to.list.expire.days}") final long allocatedToListExpireInDays) {
        this.allocatedToListExpireInDays = allocatedToListExpireInDays;
    }

    @Bean
    public CacheManager cacheManager() {
        final CaffeineCache allocatedToListCache =
                buildCache("allocatedToListCache", allocatedToListExpireInDays, TimeUnit.DAYS);
        final SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(allocatedToListCache));
        return cacheManager;
    }

    private CaffeineCache buildCache(final String name, final long expire, final TimeUnit timeUnit) {
        return new CaffeineCache(
                name, Caffeine.newBuilder().expireAfterWrite(expire, timeUnit).build());
    }
}

Service

  @Cacheable(value = "allocatedToListCache", key = "{#root.methodName}")
  public List<String> getAllocatedToList() {
    return banjoDb.jobQueueDao().findAll();
  }

  @Cacheable(value = "multipleUploadJobCache", key = "#batchId")
  public List<Long> loadJobIds(final String batchId) {
    return null; // If cache expires, there is nothing to display.
  }
sunmingtao commented 4 years ago

A better version:

@Configuration
@EnableCaching
public class CacheConfig {

    private final long batchJobExpireInMinutes;

    private final long jobMostUsedToolsExpireInDays;

    public CacheConfig(@Value("${banjo.batch.job.cache.expire.minutes}") final long batchJobExpireInMinutes,
                       @Value("${banjo.job.most.used.tools.expire.days}") final long jobMostUsedToolsExpireInDays) {
        this.batchJobExpireInMinutes = batchJobExpireInMinutes;
        this.jobMostUsedToolsExpireInDays = jobMostUsedToolsExpireInDays;
    }

    @Bean
    public CacheManager cacheManager() {
        final CaffeineCache batchJobCache = buildCache("batchJobCache", batchJobExpireInMinutes, TimeUnit.MINUTES);
        final CaffeineCache jobToolsCache = buildCache("jobToolsCache", jobMostUsedToolsExpireInDays, TimeUnit.DAYS);
        final SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(List.of(batchJobCache, jobToolsCache));
        return cacheManager;
    }

    private CaffeineCache buildCache(final String name, final long expire, final TimeUnit timeUnit) {
        return new CaffeineCache(name, Caffeine.newBuilder()
                .expireAfterWrite(expire, timeUnit)
                .build());
    }