springCache

springcache存redis乱码问题:

	1.1创建一个配置类:`@Configuration
@Cacheable(value="锁名",key="#root.methodName以方法名存入键"):此注解表示将数据保存到缓存的操作,如果缓存中有,那么该方法就不用再执行了,直接在缓存拿就好了,减少了与数据库的交互
写在需要加锁的类上。
配置类:
public class MyCacheConfig {
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration( CacheProperties cacheProperties) {
        
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
            .defaultCacheConfig();
        //指定缓存序列化方式为json
        config = config.serializeValuesWith(
            RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //设置配置文件中的各项配置,如过期时间
        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;
    }
}

application.properties的redis配置:`

spring.redis.host=127.0.0.1
spring.cache.type=redis
#设置缓存key时间
spring.cache.redis.time-to-live=3600000
#设置是否缓存null值,解决缓存穿透
spring.cache.redis.cache-null-values=true`

二、@CacheEvict(value=“那个缓存”,key=" ‘那个键’ “):此注解代表后台修改了aaa锁下的bbb键,就将aaa下的bbb缓存删除。注意key下一定要有‘’,不然会没效果
2.1 @caching:一次执行多个缓存:
eg:一次删除多个缓存:@caching(evict={
@cacheEvict(value=”“,key=” ‘’ “),
@CacheEvict(value=”“,key=” ‘’ “)
})这样就一次把这两个缓存都删除了
@CacheEvict(value=“aaaa”,allEntries=true)。一次把a下所有的缓存都删除.
所以在同一业务下value=取同名,好方便操作.@cacheEvict称失效模式
2.2@cachePut:双写模式,就是最后将查询出来的结果再放回缓存中
三、springcache不足:
缓存击穿:大量并发同时查询一个正好过期的数据,加锁,先让一个查,得到锁后再让另一个查.@Cacheable(value=”“,key=”‘’",sync=true)加锁
缓存雪崩:大量key同时过期。解决加上随机时间:spring.cache.redis.time-to-live=3600000
3.2写模式:主要缓存与数据库一致


版权声明:本文为weixin_40803117原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。