在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) {
        // 业务代码
    }
}
相关推荐
世间万物皆对象20 分钟前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了1 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·1 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic1 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王1 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
武子康1 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
qq_17448285752 小时前
springboot基于微信小程序的旧衣回收系统的设计与实现
spring boot·后端·微信小程序
转世成为计算机大神2 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式
qq_327342732 小时前
Java实现离线身份证号码OCR识别
java·开发语言
锅包肉的九珍2 小时前
Scala的Array数组
开发语言·后端·scala