您的位置:首页技术文章
文章详情页

Spring Boot集成redis,key自定义生成方式

【字号: 日期:2023-07-08 10:11:23浏览:3作者:猪猪
一)自定义redis key生成策略

@Configuration:表示当前类属于一个配置类,类似于一个spring.cfg.xml。

@EnableCaching:表示支持启用缓存。

自定义配置源码:

import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.cache.RedisCachePrefix;import org.springframework.data.redis.core.RedisTemplate; import com.alibaba.fastjson.JSON; /** * redis配置工具类 * @Configuration表示当前类属于配置类 * @EnableCaching表示支持缓存 * @author ouyangjun */@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport { /** * redis key生成策略 * target: 类 * method: 方法 * params: 参数 * @return KeyGenerator * 注意: 该方法只是声明了key的生成策略,还未被使用,需在@Cacheable注解中指定keyGenerator * 如: @Cacheable(value = 'key', keyGenerator = 'cacheKeyGenerator') */ @Bean public KeyGenerator cacheKeyGenerator() {return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) {// 由于参数可能不同, hashCode肯定不一样, 缓存的key也需要不一样sb.append(JSON.toJSONString(obj).hashCode()); } return sb.toString();}; } /** * redis全局默认配置 * @param redisTemplate * @return */ @Bean public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);redisCacheManager.setUsePrefix(true);// key缓存的前缀,以conf开头RedisCachePrefix cachePrefix = new RedisPrefix('conf');redisCacheManager.setCachePrefix(cachePrefix);// key缓存的过期时间, 600秒redisCacheManager.setDefaultExpiration(600L);return redisCacheManager; }}二)SpringBoot自带缓存方式

注解说明:

@Cacheable含义:当调用该注解声明的方法时,会先从缓存中查找,判断是否有key相同缓存的数据,如果有,就直接返回数据,如果没有,执行方法,然后把返回的数据以键值的方式存储到缓存中,方便下次同样参数请求时,直接从缓存中返回数据。

@Cacheable支持如下几个参数:

cacheNames:缓存位置的一段名称,不能为空,和value一个含义。

value:缓存位置的一段名称,不能为空,和cacheNames一个含义。

key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL。

keyGenerator:指定key的生成策略。

condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL。

@CacheEvict含义:当存在相同key的缓存时,把缓存清空,相当于删除。

@CacheEvict支持如下几个参数:

cacheNames:缓存位置的一段名称,不能为空,和value一个含义。

value:缓存位置的一段名称,不能为空,和cacheNames一个含义。

key:缓存的key,默认为空,表示使用方法的参数类型及参数值作为key,支持SpEL。

condition:触发条件,满足条件就加入缓存,默认为空,表示全部都加入缓存,支持SpEL。

allEntries:true表示清除value中的全部缓存,默认为false。

测试代码:

package hk.com.cre.process.basic.service.impl; import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable; public class RdisCacheTest { /** * 缓存测试 * 缓存生成规则: conf:redis:类名方法名参数hashcode * 注意: @Cacheable注解生成的类型在redis中默认都是string * 在每次请求的时候,都是先根据key到redis查询是否存在,如不存在则执行方法中的代码 */ @Cacheable(cacheNames = 'redis', keyGenerator = 'cacheKeyGenerator') public String getRedisString(String param1, String param2) {return param1+':'+param2; } /** * 清除缓存 */ @CacheEvict(cacheNames = 'redis', allEntries = true) public String cleanCache() {return 'success'; }}Spring Cache ? KeyGenerator自定义rediskey1. 概述

在此教程中,我们将演示如何使用 Spring Cache 创建自定义密钥生成器。

2. KeyGenerator

这负责为缓存中的每个数据项生成每个键,这些键将用于在检索时查找数据项。

此处的默认实现是SimpleKeyGenerator ?它使用提供的方法参数来生成密钥。这意味着,如果我们有两个使用相同的缓存名称和参数类型集的方法,则很有可能会导致冲突。

它还意味着缓存数据可以由另一种方法覆盖。

3. 自定义密钥生成器

密钥生成器只需要实现一个方法:

Object generate(Object object, Method method, Object... params)

如果未正确实现或使用,则可能导致覆盖缓存数据。

让我们来看看实现:

public class CustomKeyGenerator implements KeyGenerator { public Object generate(Object target, Method method, Object... params) {return target.getClass().getSimpleName() + '_' + method.getName() + '_' + StringUtils.arrayToDelimitedString(params, '_'); }}

之后,我们有两种可能的方式使用它;第一种是在应用程序Config中声明一个豆。

请务必指出,类必须从缓存配置支持或实现缓存配置程序扩展:

@EnableCaching@Configurationpublic class ApplicationConfig extends CachingConfigurerSupport { @Bean public CacheManager cacheManager() {SimpleCacheManager cacheManager = new SimpleCacheManager();Cache booksCache = new ConcurrentMapCache('books');cacheManager.setCaches(Arrays.asList(booksCache));return cacheManager; } @Bean('customKeyGenerator') public KeyGenerator keyGenerator() {return new CustomKeyGenerator(); }}

第二种方法是将其用于特定方法:

@Componentpublic class BookService { @Cacheable(value = 'books', keyGenerator = 'customKeyGenerator') public List<Book> getBooks() {List<Book> books = new ArrayList<>();books.add(new Book('The Counterfeiters', 'André Gide'));books.add(new Book('Peer Gynt and Hedda Gabler', 'Henrik Ibsen'));return books; }}4. 结论

在本文中,我们探讨了实现自定义春季缓存的密钥生成器的方法。

与往常一样,示例的完整源代码可在 GitHub 上找到。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Spring
相关文章: