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

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

有什么方法可以使用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)));
}

上面的代码将在Redis上执行这些命令,可在缓存未命中时通过MONITOR查看。再次注意EXISTS是根据以下代码执行的:

java - RedisCacheManager不更新keyspace_misses-LMLPHP

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

java - RedisCacheManager不更新keyspace_misses-LMLPHP

最佳答案

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

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