咖啡因缓存不会阻止数据库查询

Caffeine cache does not prevent from database queries

我已经在 Spring 启动应用程序中实现了咖啡因缓存的基本设置。您将在下面找到带有 @Cachable 注释的配置和服务方法。不幸的是,每次调用此方法都会生成数据库查询和缓存的新输入(使用相同的键):

Debug result with cache content

    @Cacheable(cacheNames = {"pic"})
    public PictureModel loadPictureById(String id) {
        var loadedInstance = pictureRepo.findById(id).orElseThrow(() -> new CustomNotFoundException(PictureModel.class));
        loadedInstance.setBody(pictureCompressor.decompressBytes(loadedInstance.getBody()));
        return loadedInstance;
    }

配置:

@EnableCaching
@Configuration
public class CaffeineConfig {
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("pic");
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine <Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(500)
                .expireAfterAccess(10, TimeUnit.MINUTES)
                .weakKeys()
                .recordStats();
    }
}

三次点击后的数据库查询:

Hibernate: 
    select
        picturemod0_.id as id1_10_0_,
        picturemod0_.account_id as account_5_10_0_,
        picturemod0_.body as body2_10_0_,
        picturemod0_.name as name3_10_0_,
        picturemod0_.public_platform_id as public_p6_10_0_,
        picturemod0_.service_type_id as service_7_10_0_,
        picturemod0_.type as type4_10_0_ 
    from
        image picturemod0_ 
    where
        picturemod0_.id=?
Hibernate: 
    select
        picturemod0_.id as id1_10_0_,
        picturemod0_.account_id as account_5_10_0_,
        picturemod0_.body as body2_10_0_,
        picturemod0_.name as name3_10_0_,
        picturemod0_.public_platform_id as public_p6_10_0_,
        picturemod0_.service_type_id as service_7_10_0_,
        picturemod0_.type as type4_10_0_ 
    from
        image picturemod0_ 
    where
        picturemod0_.id=?
Hibernate: 
    select
        picturemod0_.id as id1_10_0_,
        picturemod0_.account_id as account_5_10_0_,
        picturemod0_.body as body2_10_0_,
        picturemod0_.name as name3_10_0_,
        picturemod0_.public_platform_id as public_p6_10_0_,
        picturemod0_.service_type_id as service_7_10_0_,
        picturemod0_.type as type4_10_0_ 
    from
        image picturemod0_ 
    where
        picturemod0_.id=?

我想实现一次数据库查询和其他命中由缓存提供服务。

从您的 CaffeineConfig 中删除 weakKeys()

来自 weakKeys() 文档,

Warning: when this method is used, the resulting cache will use identity (==) comparison to determine equality of keys.

在您的配置中,您将键作为对象计算,但 weakKeys() 将它们与 == 进行比较,因此键匹配为不相等,并且正在发生缓存未命中。