Springboot整合SpringCache,实现对多条件查询列表进行缓存

1.导入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2.配置文件

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 3
    password: 123456
  cache:
    type: REDIS
    redis:
      time-to-live: 360000000

3.缓存配置类(让配置文件中的配置生效,并设置key和value的序列化方式)

@EnableConfigurationProperties(CacheProperties.class)  //开启配置文件支持,将CacheProperties 注册进ioc容器,相当于@Component注解
@Configuration
@EnableCaching
public class MyCacheConfig {

//    @Autowired
//    CacheProperties cacheProperties;
    /**
     *
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //key和value的序列化器
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));


        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        //让配置文件中的配置生效  ttl等
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

4.实现列表缓存

主要看下缓存的key如何设计,我本次采用 方法名称+前端传递过的查询参数 组合作为缓存的key,
比如:key=getMyCategory:categoryid:name, 当然参数可能有多个,在后面拼接即可。

	@Cacheable(value = {"categorys"}, key = "#root.methodName+':'+#request.categoryid+':'+#request.categoryiName")
    @Override
    public List<String> getMyCategory(CategoryRequest request) {
    	//查询的列表数据
    }

5.缓存数据一致性问题

保证数据库数据和redis缓存的数据一致性,常用的有双写模式,失效模式,我本次采用失效模式,采用SpringCache的@CacheEvict注解,保证数据库数据更新之后,将redis中的缓存清除,下次查询,将最新的数据放入缓存。

正当少年时,以梦为马,不负韶华!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值