首页 > 解决方案 > RedisCacheManager 未更新 keyspace_misses

问题描述

我正在使用 CacheManager 的 spring-boot spring-data-redis 1.8.9.RELEASE RedisCacheManager实现进行缓存。我想要了解的一个指标是缓存命中/未命中率。为此,我提取了通过 redis 服务器公开的keyspace_hits 和 keyspace_misses,也可以通过 redis_cli 查看INFO STATS。问题是 RedisCacheManager 从不注册缓存未命中,即 keyspace_misses 永远不会增加,即使存在缓存“未命中”。

调试代码,我看到 spring-data-redis 实际上会EXISTS在检索之前检查 redis 中的键是否存在。我看到了这种方法的意义,但是当EXISTS对 redis 服务器执行时,它不会注册缓存未命中。

有没有办法使用 RedisCacheManager 并注册缓存未命中?我知道我可以使用其他 redis 对象来完成此操作,但我想知道是否可以使用标准 CacheManager 实现来完成?

编辑

理想的解决方案不会增加大量开销,而且我无法编辑 redis 服务器的配置。

RedisCacheManager 从缓存中检索元素时使用的代码。注意事项Boolean exists

public RedisCacheElement get(final RedisCacheKey cacheKey) {
    Assert.notNull(cacheKey, "CacheKey must not be null!");
    Boolean exists = (Boolean)this.redisOperations.execute(new RedisCallback<Boolean>() {
        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.exists(cacheKey.getKeyBytes());
        }
    });
    return !exists ? null : new RedisCacheElement(cacheKey, this.fromStoreValue(this.lookup(cacheKey)));
}

MONITOR上面的代码将通过缓存未命中在可查看的 redis 上执行这些命令。再次注意EXISTS按代码执行:

为缓存未命中执行的 Redis 命令

执行上述命令后,keyspace_misses即使缓存未命中,也不会递增:

在此处输入图像描述

标签: javaspringspring-bootredisspring-data-redis

解决方案


问题中提到的代码是Spring提供的RedisCache的一部分。

  1. 扩展并创建 RedisCache 类的自定义实现,以覆盖“get”方法的行为以满足您的需要。
  2. 扩展 RedisCacheManager 以覆盖方法“createRedisCache”以使用您在第一步中创建的自定义 RedisCache 而不是默认缓存。

推荐阅读