在SpringBoot项目中应用RedisCache功能

1.application.yaml中添加cache配置

XML 复制代码
spring:
  cache:
    type: redis
    redis:
      time-to-live: 72000000
      key-prefix: 'redis:cache:'
      use-key-prefix: true
      cache-null-values: true

2.封装RedisCache配置类

java 复制代码
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class RedisCacheConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // config = config.entryTtl();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //将配置文件中所有的配置都生效
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.computePrefixWith(cacheName -> redisProperties.getKeyPrefix() + cacheName);
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }
}

3.封装RedisCache缓存Key生成器

java 复制代码
/**
 * @ClassName redisCacheKeyGenerator
 * @description: Redis缓存key 生成策略
 */
@Slf4j
@Component("redisCacheKeyGenerator")
public class RedisCacheKeyGenerator implements KeyGenerator {

    private final static int NO_PARAM_KEY = 0;
    public static final char SP = ':';
	
    @Autowired(required = false)
    private CacheManager cacheManager;

    @PostConstruct
    public void init() {
        log.info("cacheManager:{}",cacheManager);
    }

    @Override
    public Object generate(Object target, Method method, Object... parameters) {
        StringBuilder strBuilder = new StringBuilder(30);
        // 类名
        strBuilder.append(SP);
        // 方法名
        strBuilder.append(method.getName());
        strBuilder.append(SP);
        if (parameters.length > 0) {
            // 参数值
            for (Object object : parameters) {
                if (isSimpleValueType(object.getClass())) {
                    strBuilder.append(object);
                } else {
                    strBuilder.append(JSONUtil.toJsonStr(object).hashCode());
                }
            }
        } else {
            strBuilder.append(NO_PARAM_KEY);
        }
        log.info("生成缓存序列:{}",strBuilder);
        return strBuilder.toString();
    }

    /**
     * 判断是否是简单值类型.包括:基础数据类型、CharSequence、Number、Date、URL、URI、Locale、Class;
     *
     * @param clazz
     * @return
     */
    public static boolean isSimpleValueType(Class<?> clazz) {
        return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() || CharSequence.class.isAssignableFrom(clazz)
                || Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || URI.class == clazz
                || URL.class == clazz || Locale.class == clazz || Class.class == clazz);
    }

}

4.Service类中应用RedisCache

java 复制代码
@Service
@CacheConfig(cacheNames = "productAlbum",keyGenerator = "redisCacheKeyGenerator")
public class ProductAlbumServiceImpl extends ServiceImpl<ProductAlbumMapper, ProductAlbum> implements IProductAlbumService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Caching(
            evict = {
                    @CacheEvict(key = "':getAlbumPics_'+#productSn"),
                    @CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
            }
    )
    public void saveAlbumPics(String productSn, String pic) {
        // 业务代码
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = "':getAlbumPics_'+#productSn"),
                    @CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
            }
    )
    public void doAlbumPics(String productSn,List<ProductAlbumResp> albumList) {
       // 业务代码
    }

    @Override
    @Cacheable(key = "':getAlbumPics_'+#productSn")
    public String getAlbumPics(String productSn) {
        // 业务代码
    }

    @Override
    @Cacheable(key = "':getAlbumPicsBySn_'+#productSn")
    public List<ProductAlbumResp> getAlbumPicsBySn(String productSn) {
       // 业务代码
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = "':getAlbumPics_'+#productSn"),
                    @CacheEvict(key = "':getAlbumPicsBySn_'+#productSn")
            }
    )
    public void saveAlbumPicsByNotExist(String productSn, String pic) {
        // 业务代码
    }
}
相关推荐
ITPUB-微风8 分钟前
美团MTSQL特性解析:技术深度与应用广度的完美结合
java·服务器·开发语言
WeiLai111217 分钟前
面试基础--微服务架构:如何拆分微服务、数据一致性、服务调用
java·分布式·后端·微服务·中间件·面试·架构
非 白1 小时前
【Java】单例模式
java·笔记·单例模式
尚学教辅学习资料1 小时前
基于SpringBoot+vue+uniapp的智慧旅游小程序+LW示例参考
vue.js·spring boot·uni-app·旅游
IDRSolutions_CN1 小时前
如何在 PDF 文件中嵌入自定义数据
java·经验分享·pdf·软件工程·团队开发
_风中无我。1 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
bing_1582 小时前
Spring Boot 中为什么 需要限流、降级和熔断?
java
猿java2 小时前
很多程序员会忽略的问题:创建 MySQL索引,需要注意什么?
java·后端·mysql
ccm032 小时前
高效开发助手:深入了解Hutool工具库
java·g工具库
大脑经常闹风暴@小猿2 小时前
1.1 go环境搭建及基本使用
开发语言·后端·golang