Search code examples
springspring-cache

Spring cache eviction with scheduled annotation


In the following code cache works, but eviction does not work, could you approach me? I have read following link: Schedule Spring cache eviction?

@Component
@RequiredArgsConstructor
public class CacheInvalidator {

    @Scheduled(fixedRate = 1000L)
    public void evictCache() {
       clearCache();
    }

    @CacheEvict(value = "count", allEntries = true)
    public void clearCache() {
    }
}

@Component
@RequiredArgsConstructor
public class ARepositoryImpl implements ARepository {

    @Cacheable(value = "count")
    public Integer count() {
        return jdbcTemplate.queryForObject("...", Integer.class);
    }
}

@SpringBootApplication
@EnableMongoRepositories
@EnableScheduling
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

in pom.xml:

   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.2.2.RELEASE</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>

Solution

  • It does not work because method evictCache in CacheInvalidator calls clearCache not on Spring's proxy but on original object and that method does nothing despite being annotated with @CacheEvict(value = "count", allEntries = true).

    Instead of:

    @Component
    @RequiredArgsConstructor
    public class CacheInvalidator {
    
        @Scheduled(fixedRate = 1000L)
        public void evictCache() {
           clearCache();
        }
    
        @CacheEvict(value = "count", allEntries = true)
        public void clearCache() {
        }
    }
    

    try:

    @Component
    @RequiredArgsConstructor
    public class CacheInvalidator {
    
        @Scheduled(fixedRate = 1000L)
        @CacheEvict(value = "count", allEntries = true)
        public void clearCache() {
        }
    
    }