@Cacheable缓存,自定义分组缓存时间、自定义缓存key(读取类+方法+参数)

参考:SpringBoot 缓存之 @Cacheable介绍-CSDN博客

java 复制代码
package com.ruoyi.project.tool.cache;

import com.ruoyi.project.system.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redisTest")
@Slf4j
public class CacheTestController {

//    http://localhost:9876/redisTest/cache?userId=6&userName=zhangsan
    @GetMapping("/cache")
    @Cacheable(cacheNames = "User", keyGenerator = "cacheKeyGenerator")
    public Object cache(SysUser sysUser){
        log.info("sysUser: {}", sysUser);
        return sysUser;
    }
}
复制代码
CacheConfig
java 复制代码
package com.ruoyi.framework.config.cache;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableCaching
public class CacheConfig {

    /**
     * CacheManager为一个接口,RedisCacheManager为该接口的实现
     * redisConnectionFactory 连接工厂
     * cacheDefaults 默认配置
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfig(10000))
                .withInitialCacheConfigurations(initCacheConfigMap())
                .transactionAware()
                .build();
        return redisCacheManager;

    }

    /**
     * 默认配置中进行了序列化的配置
     *
     * @param second
     * @return
     */
    private RedisCacheConfiguration defaultCacheConfig(Integer second) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //配置序列化 解决乱码的问题
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(second))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        return config;

    }

    /**
     * 针对不同的redis的key 有不同的过期时间
     *
     * @return
     */
    private Map<String, RedisCacheConfiguration> initCacheConfigMap() {

        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("User", this.defaultCacheConfig(10 * 60));
        configMap.put("User1", this.defaultCacheConfig(1000));
        return configMap;
    }

}
复制代码
CacheKeyGenerator
java 复制代码
package com.ruoyi.framework.config.cache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;


@Slf4j
@Component
public class CacheKeyGenerator implements KeyGenerator {

    @Override
    public Object generate(Object target, Method method, Object... params) {
//        log.info("===CacheKeyGenerator generate 19 --->target: {}, method: {}, params: {}", target, method, params);
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName())
                .append(".")
                .append(method.getName())
                .append(":")
                .append(StringUtils.arrayToDelimitedString(params, "_"));// !注意,记得重写参数的toString哦
        log.info("===CacheKeyGenerator generate 27 --->sb: {}", sb);
        return sb.toString();
    }
}
相关推荐
vx+_bysj686913 小时前
【免费领源码】基于Springboot白隼校园音乐点歌系统 计算机毕业设计项目推荐上万套实战教程JAVA,node.js,C++、python、大屏数据可视化
java·spring boot·mysql·课程设计
jay神14 小时前
基于SpringBoot的英语自主学习系统
java·spring boot·后端·学习·毕业设计
sww_102614 小时前
Spring AI 可观测性实战
java·人工智能·spring
qinaoaini14 小时前
Spring 简介
java·后端·spring
dfyx99914 小时前
SpringBoot教程(三十二) SpringBoot集成Skywalking链路跟踪
spring boot·后端·skywalking
全栈前端老曹14 小时前
【Redis】Redis 客户端连接与编程实践——Python/Java/Node.js 连接 Redis、实现计数器、缓存接口
前端·数据库·redis·python·缓存·全栈
1candobetter14 小时前
JAVA后端开发——反射机制在Spring业务开发中的实际应用
java·开发语言·spring
九转苍翎14 小时前
微服务学习笔记(1)——SpringColud概述
spring boot·maven·springcloud
鸡蛋豆腐仙子15 小时前
redis及实现分布式锁的原理
java·redis·分布式·学习·缓存
墨染青竹梦悠然15 小时前
基于SpringBoot + vue的农产品销售系统(华夏鲜仓)
vue.js·spring boot·python·django·毕业设计·毕设