首页 > 解决方案 > 带有弹簧靴的咖啡因缓存不起作用

问题描述

我已经使用咖啡因缓存设置了一个场景,但我无法让它工作,当参数相同时,总是调用真正的方法。这是我的配置:

pom.xml

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

CacheManager 的配置类

@Configuration
@EnableCaching
public class CachingConfig {

    public static final String CACHE_NAME = "test";

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager(CACHE_NAME);
        cacheManager.setCaffeine(caffeineConfig());
        return cacheManager;
    }

    private Caffeine caffeineConfig() {
        return Caffeine.newBuilder()
                .expireAfterAccess(10, TimeUnit.MINUTES)
                .maximumSize(1024 * 1024 * 256);
    }
}

然后是具有可缓存方法的类:

@CacheConfig(cacheNames = {CachingConfig.CACHE_NAME})
public class MyClass{

  @Cacheable
   public Object cacheableMethod(String a, String b, Boolean c) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Object()
}

我还尝试将缓存名称添加到 Cacheable 注释中:

@Cacheable(value = CachingConfig.CACHE_NAME)

并移至@EnableCachingSpring Boot 主应用程序类。

真正的方法总是被调用。

关于我做错了什么的任何想法?

谢谢

标签: spring-bootcaffeine-cache

解决方案


@Cacheable 方法必须位于@Bean、@Component、@Service 内部...


推荐阅读