I am using RedisTemplate for caching purpose in my spring boot service. Now I want to check cache hit/cache miss through end point actuator/prometheus. But can not see cache hit/cache miss for the cache.
The code I have written is something like below
@EnableCaching
@Configuration
public class CachingConfiguration {
@Bean
public RedisTemplate<String, SomeData> redisTemplate(LettuceConnectionFactory connectionFactory, ObjectMapper objectMapper)
{
RedisTemplate<String, SomeData> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
var valueSerializer = new Jackson2JsonRedisSerializer<SomeData>(SomeData.class);
valueSerializer.setObjectMapper(objectMapper);
template.setValueSerializer(valueSerializer);
return template;
}
}
Now am doing like below to get and save into cache
to get:-
redisTemplate.opsForValue().get(key);
And to save:-
redisTemplate.opsForValue().set(key, obj, some_time_limit);
My cache is working properly, am getting able to save into cache and getting proper data.
But I don’t see cache hit/miss related data inside actuator/prometheus.
In my application.yml file I have added below
cache:
redis:
enable-statistics: 'true'
2
Answers
I would assume that in order for
Springboot Cache Monitoring
to apply (Including Hits/Misses), you would need to depend onAutoConfiguration
.In your case you are creating the RedisTemplate yourself, and probably enable-statistics is not actually applied.
Can you remove the redistemplate creation and use
@Cacheable
annotation abstraction? That way any supported Cache library will work out of the box, without you having to create@Bean
and manually configuring it.Otherwise, generally if you wanted to enable statistics on a cache manager manually, you will need to call
RedisCacheManager.RedisCacheManagerBuilder enableStatistics()
:https://docs.spring.io/spring-data/redis/docs/current/api/org/springframework/data/redis/cache/RedisCacheManager.RedisCacheManagerBuilder.html
For Reference:
I had exactly the same question and spent a good number of hours trying to figure out how to enable cache metrics for my manually created
RedisTemplate
instance.What I eventually realised is that it’s only
RedisCache
class which collects and exposesCacheStatistics
throughgetStatistics()
method. As far as I can see there is nothing like that forRedisTemplate
, which means you either need to switch to usingRedisCache
throughRedisCacheManager
and@Cacheable
annotation or implement your custom metrics collection.