带预定注释的Spring缓存逐出

问题描述 投票:0回答:1

在下面的代码缓存中有效,但是强制收回无效,您可以接近我吗?我已阅读以下链接: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);
    }
}

在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>
spring spring-cache
1个回答
0
投票

这不起作用,因为evictCache中的方法CacheInvalidator不是在Spring的代理上而是在原始对象上调用clearCache,尽管该方法用@CacheEvict(value = "count", allEntries = true)进行了注释,但该方法没有任何作用。

而不是:

@Component
@RequiredArgsConstructor
public class CacheInvalidator {

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

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

尝试:

@Component
@RequiredArgsConstructor
public class CacheInvalidator {

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

}
© www.soinside.com 2019 - 2024. All rights reserved.