springboot @Cacheable注解实现Redis缓存

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

 

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

1
redisTemplate.opsForHash().putAll(hashKeyPrefix, hashData);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@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 @   每月工资一万八  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示