在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) {
        // 业务代码
    }
}
相关推荐
xyliiiiiL9 分钟前
一文总结常见项目排查
java·服务器·数据库
shaoing11 分钟前
MySQL 错误 报错:Table ‘performance_schema.session_variables’ Doesn’t Exist
java·开发语言·数据库
Asthenia041212 分钟前
由浅入深解析Redis事务机制及其业务应用-电商场景解决超卖
后端
Asthenia041213 分钟前
Redis详解:从内存一致性到持久化策略的思维链条
后端
Asthenia041213 分钟前
深入剖析 Redis 持久化:RDB 与 AOF 的全景解析
后端
Apifox24 分钟前
如何在 Apifox 中通过 CLI 运行包含云端数据库连接配置的测试场景
前端·后端·程序员
掘金一周31 分钟前
金石焕新程 >> 瓜分万元现金大奖征文活动即将回归 | 掘金一周 4.3
前端·人工智能·后端
uhakadotcom1 小时前
构建高效自动翻译工作流:技术与实践
后端·面试·github
腥臭腐朽的日子熠熠生辉1 小时前
解决maven失效问题(现象:maven中只有jdk的工具包,没有springboot的包)
java·spring boot·maven
Asthenia04121 小时前
深入分析Java中的AQS:从应用到原理的思维链条
后端