我使用spring boot和redis进行缓存。我可以缓存使用@Cacheable(key = "{#input,#page,#size}",value = "on_test")
从数据库(oracle)获取的数据。当我尝试使用redisTemplate从key("on_test::0,0,10")
获取数据时,结果为0为什么?
Redis配置:
@Configuration
public class RedisConfig {
@Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
redisStandaloneConfiguration.setPassword(RedisPassword.of("admin@123"));
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<String,Objects> redisTemplate() {
RedisTemplate<String,Objects> template = new RedisTemplate<>();
template.setStringSerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
//service
@Override
@Cacheable(key = "{#input,#page,#size}",value = "on_test")
public Page<?> getAllByZikaConfirmedClinicIs(Integer input,int page,int size) {
try {
Pageable newPage = PageRequest.of(page, size);
String fromCache = controlledCacheService.getFromCache();
if (fromCache == null && input!=null) {
log.info("cache is empty lets initials it!!!");
Page<DataSet> all = dataSetRepository.getAllByZikaConfirmedClinicIs(input,newPage);
List<DataSet> d = redisTemplate.opsForHash().values("on_test::0,0,10");
System.out.print(d);
return all;
}
return null;
使用@Cacheable
的全部要点是您不需要直接使用RedisTemplate
。您只需要调用getAllByZikaConfirmedClinicIs()
(从其定义的类的外部),Spring将首先自动检查是否有缓存的结果,然后返回该结果,而不是调用该函数。
如果这不起作用,是否用@EnableCaching
注释了其中一个Spring Boot配置类以启用缓存?