springboot @Cacheable注解实现Redis缓存

https://www.cnblogs.com/manmanblogs/p/15686332.html

 

不过查询完数据存到redis是默认以String类型,如果想转hash,需自定义

redisTemplate.opsForHash().putAll(hashKeyPrefix, hashData);  
@Service  
public class PopularProductService {  
  
    @Autowired  
    private RedisTemplate<String, Object> redisTemplate;  
  
    @Autowired  
    private PopularProductMapper baseMapper;  
  
    // 使用@Cacheable注解来获取缓存,但不会自动存储为Hash  
    @Cacheable(value = "KEY:POPULARPRODUCT", key = "#page.current")  
    public IPage<PopularProductResult> getPopularProduct(Page page) {  
        // 这里假设baseMapper.getPopularProduct方法会返回一个新的Page对象  
        IPage<PopularProductResult> popularProducts = this.baseMapper.getPopularProduct(page);  
  
        // 自定义逻辑来将Page对象转换为Redis Hash并存储  
        storeAsRedisHash("KEY:POPULARPRODUCT:" + page.getCurrent(), popularProducts);  
  
        return popularProducts;  
    }  
  
    private void storeAsRedisHash(String hashKeyPrefix, IPage<PopularProductResult> popularProducts) {  
        // 假设你有一个方法可以将IPage转换为Map<String, Object>  
        Map<String, Object> hashData = convertToHashData(popularProducts);  
  
        // 使用RedisTemplate来存储Hash数据  
        StringRedisSerializer stringSerializer = new StringRedisSerializer();  
        redisTemplate.setKeySerializer(stringSerializer);  
        redisTemplate.setHashKeySerializer(stringSerializer);  
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));  
  
        redisTemplate.opsForHash().putAll(hashKeyPrefix, hashData);  
    }  
  
    // 你需要实现这个方法,将IPage转换为适合存储在Redis Hash中的Map  
    private Map<String, Object> convertToHashData(IPage<PopularProductResult> popularProducts) {  
        // ... 实现转换逻辑  
        return hashData; // 返回一个Map,其键和值都是字符串或可序列化的对象  
    }  
}

  

posted @ 2024-06-29 16:52  每月工资一万八  阅读(222)  评论(0)    收藏  举报