千家信息网

springboot2.x怎么集成缓存注解及设置过期时间

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,本篇内容介绍了"springboot2.x怎么集成缓存注解及设置过期时间"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅
千家信息网最后更新 2025年12月02日springboot2.x怎么集成缓存注解及设置过期时间

本篇内容介绍了"springboot2.x怎么集成缓存注解及设置过期时间"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

添加以下配置信息;

/** * 基于注解添加缓存 */@Configuration@EnableCachingpublic class CacheConfig extends CachingConfigurerSupport {    private final RedisConnectionFactory redisConnectionFactory;    CacheConfig(RedisConnectionFactory redisConnectionFactory) {        this.redisConnectionFactory = redisConnectionFactory;    }    @Bean    @Override    public KeyGenerator keyGenerator() {        return (o, method, objects) -> {            StringBuilder sb = new StringBuilder(32);            sb.append(o.getClass().getSimpleName());            sb.append(".");            sb.append(method.getName());            if (objects.length > 0) {                sb.append("#");            }            String sp = "";            for (Object object : objects) {                sb.append(sp);                if (object == null) {                    sb.append("NULL");                } else {                    sb.append(object.toString());                }                sp = ".";            }            return sb.toString();        };    }    /**     * 配置 RedisCacheManager,使用 cache 注解管理 redis 缓存     */    @Bean    @Override    public CacheManager cacheManager() {        // 初始化一个RedisCacheWriter        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);        // 设置默认过期时间:30 分钟        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofMinutes(30))                // .disableCachingNullValues()                // 使用注解时的序列化、反序列化                .serializeKeysWith(MyRedisCacheManager.STRING_PAIR)                .serializeValuesWith(MyRedisCacheManager.FASTJSON_PAIR);        return new MyRedisCacheManager(cacheWriter, defaultCacheConfig);    }}
redis配置信息:
@Configuration@ConditionalOnClass(RedisOperations.class)@EnableConfigurationProperties(RedisProperties.class)@Import({LettuceConnectionConfiguration.class})public class RedisConfig {    @Bean    @ConditionalOnMissingBean(name = "redisTemplate")    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {        RedisTemplate template = new RedisTemplate<>();        // set key serializer        StringRedisSerializer serializer = MyRedisCacheManager.STRING_SERIALIZER;        // 设置key序列化类,否则key前面会多了一些乱码        template.setKeySerializer(serializer);        template.setHashKeySerializer(serializer);        // fastjson serializer        GenericFastJsonRedisSerializer fastSerializer = MyRedisCacheManager.FASTJSON_SERIALIZER;        template.setValueSerializer(fastSerializer);        template.setHashValueSerializer(fastSerializer);        // 如果 KeySerializer 或者 ValueSerializer 没有配置,则对应的 KeySerializer、ValueSerializer 才使用这个 Serializer        template.setDefaultSerializer(fastSerializer);        // factory        template.setConnectionFactory(redisConnectionFactory);        template.afterPropertiesSet();        return template;    }    @Bean    @ConditionalOnMissingBean    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {        StringRedisTemplate template = new StringRedisTemplate();        template.setConnectionFactory(redisConnectionFactory);        return template;    }}
重写RedisCacheManager
public class MyRedisCacheManager extends RedisCacheManager implements ApplicationContextAware, InitializingBean {    private static final Logger LOGGER = LoggerFactory.getLogger(MyRedisCacheManager.class);    private ApplicationContext applicationContext;    private Map initialCacheConfiguration = new LinkedHashMap<>();    /**     * key serializer     */    public static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();    /**     * value serializer     * 
     *     使用 FastJsonRedisSerializer 会报错:java.lang.ClassCastException     *     FastJsonRedisSerializer fastSerializer = new FastJsonRedisSerializer<>(Object.class);     *      */    public static final GenericFastJsonRedisSerializer FASTJSON_SERIALIZER = new GenericFastJsonRedisSerializer();    /**     * key serializer pair     */    public static final RedisSerializationContext.SerializationPair STRING_PAIR = RedisSerializationContext            .SerializationPair.fromSerializer(STRING_SERIALIZER);    /**     * value serializer pair     */    public static final RedisSerializationContext.SerializationPair FASTJSON_PAIR = RedisSerializationContext            .SerializationPair.fromSerializer(FASTJSON_SERIALIZER);    public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {        super(cacheWriter, defaultCacheConfiguration);    }    @Override    public Cache getCache(String name) {        Cache cache = super.getCache(name);        return new RedisCacheWrapper(cache);    }    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }    @Override    public void afterPropertiesSet() {        String[] beanNames = applicationContext.getBeanNamesForType(Object.class);        for (String beanName : beanNames) {            final Class clazz = applicationContext.getType(beanName);            add(clazz);        }        super.afterPropertiesSet();    }    @Override    protected Collection loadCaches() {        List caches = new LinkedList<>();        for (Map.Entry entry : initialCacheConfiguration.entrySet()) {            caches.add(super.createRedisCache(entry.getKey(), entry.getValue()));        }        return caches;    }    private void add(final Class clazz) {        ReflectionUtils.doWithMethods(clazz, method -> {            ReflectionUtils.makeAccessible(method);            CacheExpire cacheExpire = AnnotationUtils.findAnnotation(method, CacheExpire.class);            if (cacheExpire == null) {                return;            }            Cacheable cacheable = AnnotationUtils.findAnnotation(method, Cacheable.class);            if (cacheable != null) {                add(cacheable.cacheNames(), cacheExpire);                return;            }            Caching caching = AnnotationUtils.findAnnotation(method, Caching.class);            if (caching != null) {                Cacheable[] cs = caching.cacheable();                if (cs.length > 0) {                    for (Cacheable c : cs) {                        if (cacheExpire != null && c != null) {                            add(c.cacheNames(), cacheExpire);                        }                    }                }            } else {                CacheConfig cacheConfig = AnnotationUtils.findAnnotation(clazz, CacheConfig.class);                if (cacheConfig != null) {                    add(cacheConfig.cacheNames(), cacheExpire);                }            }        }, method -> null != AnnotationUtils.findAnnotation(method, CacheExpire.class));    }    private void add(String[] cacheNames, CacheExpire cacheExpire) {        for (String cacheName : cacheNames) {            if (cacheName == null || "".equals(cacheName.trim())) {                continue;            }            long expire = cacheExpire.expire();            LOGGER.info("cacheName: {}, expire: {}", cacheName, expire);            if (expire >= 0) {                // 缓存配置                RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()                        .entryTtl(Duration.ofSeconds(expire))                        .disableCachingNullValues()                        // .prefixKeysWith(cacheName)                        .serializeKeysWith(STRING_PAIR)                        .serializeValuesWith(FASTJSON_PAIR);                initialCacheConfiguration.put(cacheName, config);            } else {                LOGGER.warn("{} use default expiration.", cacheName);            }        }    }    protected static class RedisCacheWrapper implements Cache {        private final Cache cache;        RedisCacheWrapper(Cache cache) {            this.cache = cache;        }        @Override        public String getName() {            // LOGGER.info("name: {}", cache.getName());            try {                return cache.getName();            } catch (Exception e) {                LOGGER.error("getName ---> errmsg: {}", e.getMessage(), e);                return null;            }        }        @Override        public Object getNativeCache() {            // LOGGER.info("nativeCache: {}", cache.getNativeCache());            try {                return cache.getNativeCache();            } catch (Exception e) {                LOGGER.error("getNativeCache ---> errmsg: {}", e.getMessage(), e);                return null;            }        }        @Override        public ValueWrapper get(Object o) {            // LOGGER.info("get ---> o: {}", o);            try {                return cache.get(o);            } catch (Exception e) {                LOGGER.error("get ---> o: {}, errmsg: {}", o, e.getMessage(), e);                return null;            }        }        @Override        public  T get(Object o, Class aClass) {            // LOGGER.info("get ---> o: {}, clazz: {}", o, aClass);            try {                return cache.get(o, aClass);            } catch (Exception e) {                LOGGER.error("get ---> o: {}, clazz: {}, errmsg: {}", o, aClass, e.getMessage(), e);                return null;            }        }        @Override        public  T get(Object o, Callable callable) {            // LOGGER.info("get ---> o: {}", o);            try {                return cache.get(o, callable);            } catch (Exception e) {                LOGGER.error("get ---> o: {}, errmsg: {}", o, e.getMessage(), e);                return null;            }        }        @Override        public void put(Object o, Object o1) {            // LOGGER.info("put ---> o: {}, o1: {}", o, o1);            try {                cache.put(o, o1);            } catch (Exception e) {                LOGGER.error("put ---> o: {}, o1: {}, errmsg: {}", o, o1, e.getMessage(), e);            }        }        @Override        public ValueWrapper putIfAbsent(Object o, Object o1) {            // LOGGER.info("putIfAbsent ---> o: {}, o1: {}", o, o1);            try {                return cache.putIfAbsent(o, o1);            } catch (Exception e) {                LOGGER.error("putIfAbsent ---> o: {}, o1: {}, errmsg: {}", o, o1, e.getMessage(), e);                return null;            }        }        @Override        public void evict(Object o) {            // LOGGER.info("evict ---> o: {}", o);            try {                cache.evict(o);            } catch (Exception e) {                LOGGER.error("evict ---> o: {}, errmsg: {}", o, e.getMessage(), e);            }        }        @Override        public void clear() {            // LOGGER.info("clear");            try {                cache.clear();            } catch (Exception e) {                LOGGER.error("clear ---> errmsg: {}", e.getMessage(), e);            }        }    }}

应用:

@GetMapping("/getShopByShopNO/{shopNo}")public Mono getShopByShopNO(@PathVariable("shopNo") final String shopNo){    final ShopDO shopByShopNO = shopDAO.getShopByShopNO(shopNo);    return Mono.just(shopByShopNO);}/** * 查询店铺详情 * @param shopNo * @return*/@Cacheable(value = "shop",key = "'shop_'.concat(#root.args[0])",sync = true)@CacheExpire(30)ShopDO getShopByShopNO(String shopNo);

参考:https://www.cnblogs.com/wjwen/p/9301119.html

"springboot2.x怎么集成缓存注解及设置过期时间"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

注解 缓存 配置 时间 序列 信息 内容 更多 知识 实用 学有所成 接下来 乱码 困境 实际 店铺 情况 文章 案例 编带 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 sql创建学生数据库 平安的软件开发 广东互联网网络技术服务哪家好 无法链接服务器什么意思 哪种网络技术是主干网优选 vba 数据库查询遍历 我军重大网络安全事件 速达软件数据库坏了咋修复 服务器在下载过程中错误 学习游戏软件开发要具备什么 软件开发家装工装接口名称 南宁互动博物馆软件开发 电脑服务器主板坏了能修好么 河南省商丘市网络安全检查 光汇石油软件开发怎么样 观看网络安全活动有感 重要保障期间网络安全 软件开发需要互联网技术 宝安区无源网络技术开发服务价格 广东省游戏行业网络安全 山东计算机网络技术大学学什么 java对数据库中的成绩排序 安防领域网络安全防护主流 软件开发部门业绩 46届世界技能大赛网络安全 淘宝 ip 数据库 三级网络技术好过么 成都网络安全学会电话 网络安全是本质在什么 软件开发环境建设
0