缓存常见问题+spring cache使用

缓存问题:

1.缓存穿透:客户查不存在的数据,那么就不会经过缓存,查完值为null,不会把值保存到缓存中,下次查还是查数据库
2.缓存雪崩:多个缓存同时过期,刚好过期的时刻有大量请求,请求不经缓存,数据库压力过大奔溃
3.缓存击穿:大量请求访问同一资源,刚好缓存过期,大量请求经数据库,压力过大
4.缓存一致性:请求修改了数据库,缓存还是原数据

解决办法:
1、解决缓存穿透:空结果缓存,这样就不会一直访问数据库了
2、解决缓存雪崩:设置过期时间(加随机值),1~5分钟,不会造成缓存大面积过期
3、解决缓存击穿:加锁,只让一人访问数据库,得到的结果放缓存,其他人访问缓存
4、解决缓存一致性:大部分修改较少的业务,设置过期时间即可,少部分加读写锁 或者 cannal订阅binlog【数据库一修改,就让缓存同步修改】
也可以选择采用两种模式:双写模式(修改数据库之后修改缓存),失效模式(修改数据库之后让缓存失效)
【但也有问题,双写模式:如果先修改的修改慢,后修改的修改快,缓存先经过后面修改的再经过前面修改的,导致缓存只被前者修改。
失效模式:第一次修改,把缓存删除。第二次修改,修改速度慢,还没改完数据库就有读的请求过来。这个请求获取到的是第一次修改后的数据。这时第二次修改把缓存失效,读的请求把数据写入缓存,缓存仍然是第一次修改的。
可以延迟几百毫秒,再写入redis中,那么上面的问题就可以解决!
所以,要么加锁,要么不用缓存,但是加锁的效率很低,还不如直接查数据库】

我们系统的一致性解决方案:
1、缓存的所有数据都有过期时间,数据过期下一次查询触发主动更新
2、读写数据的时候,加上分布式的读写锁。
【面试题答案】

spring cache

sring cashe对缓存各种问题的解决:
1.缓存穿透:查询一个nulL数据。解决:缓存空数据;【配置:spring.cache.redis.cache-null-values=true】
2.缓存击穿:大量并发进来同时查询一个正好过期的数据。解决:加锁;【默认不加。可以用:@Cacheable(value = {“”} , key = “”,sync = true)】【前面加本地锁】
3.缓存雪崩:大量的key同时过期。解决:加随机时间。其实加上过期时间就足够了。【配置:spring.cache.redis.time-to-live=3600000】

默认行为:
1.如果缓存中没有,不会调用方法
2.默认生成的key结构: 缓存分区的名字::simpleKey[] (自主生成的key值)【如果指定了前缀,那么就不会用缓存分区的名字,而是用前缀】
【最好不用前缀】
3.缓存的key值:默认使用jdk序列化机制,将序列化后的数据存到redis(不是json格式)
4.默认ttl时间:-1 (永远不过期)

自定义:
1.指定缓存用的key:key属性指定,使用spel表达式,如:
@Cacheable(value = {“category”} , key = “‘aaa’”) 字符串需要用单引号圈起来,redis中的key为:category::aaa
@Cacheable(value = {“category”} , key = “#root.methodName”) 使用方法名作为key
2.指定缓存的存活时间:配置文件:
spring.cache.redis.time-to-live=3600000 单位毫秒
3.将数据保存为json格式:
加配置类

导入spring cache 和 redis 依赖

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

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

写配置文件

# 缓存类型
spring.cache.type=redis
# 缓存过期时间
spring.cache.redis.time-to-live=3600000
# 前缀,便于与redis中存的其他东西区分  【如果指定了前缀,那么就不会用缓存分区的名字,而是用前缀】
# spring.cache.redis.key-prefix=CACHE_
# 是否使用前缀 默认true
# spring.cache.redis.use-key-prefix=true
# 是否缓存空值,防止缓存击穿
spring.cache.redis.cache-null-values=true


# redis配置
spring.redis.host=192.168.190.150
spring.redis.port=6379

缓存配置类

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

// 绑定配置文件?
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
// 开启缓存注解
@EnableCaching
public class MyCacheConfig {

    @Bean
    // 可以直接通过参数传入配置类
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        // key还是用jdk字符串存
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        // value用json字符串
        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.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return  config;
    }
}

使用缓存
@Cacheable:Triggers cache population.,:触发将数据保存到缓存的操作
@CacheEvict:Triggers cache eviction,:触发将数据从缓存删除的操作【配合上一个,配在写方法上,失效模式】
@CachePut:Updates the cache without interfering with the method execution,:不影响方法执行更新鍰存【配合上一个,配在写方法上,双写模式】
@Caching:Regroups multiple cache operations to beapplied on a method.:组合以上多个操作
@CacheConfig:Shares some common cache-relatedings at class-Level,:在类级别共享缓存的相同配置

大坑!!!:http://t.csdn.cn/ovrrk
类调用本类加缓存的方法不走缓存!!!、
解决办法:
0)、导入 spring-boot-starter-aop 依赖

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

1)、启动类加注解:

​ @EnableTransactionManagement(proxyTargetClass = true)

​ @EnableAspectJAutoProxy(exposeProxy=true)

3)、使用 AopContext.currentProxy() 生成当前类的代理对象,再调用本类方法

ProductServiceIml o = (ProductServiceIml)AopContext.currentProxy ();
o.getFirPageProductVo (1,pageSize);

@Cacheable

// 每一个需要缓存数据我们都要指定放到哪个分区【按照业务类型分】
//代表当前的方法需要缓存。如果有缓存则不进行操作,没有缓存,会调用方法,将结果放到缓存中
// 可以写多个分区的名字,表示在这些分区都缓存一份
@Cacheable(value = {"category"} , key = "#root.methodName")
@Override
public List<CategoryEntity> getLevel1Categorys() {
    List<CategoryEntity> selectList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));


    return selectList;
}

加本地锁,解决缓存击穿 【sync = true】

@Cacheable(value = {"category"} , key = "#root.Method",sync = true)

@CacheEvict 【配合上面那个,构成失效模式】【要注意有没有加前缀,没测试这种情况】

@CacheEvict(value = {"category"} , key = "'getLevel1Categorys'") // 注意字符串要加单引号
@Transactional
@Override
public void updateCascade(CategoryEntity category) {
    this.updateById(category);
    categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
}

(删除整个缓存分区下的数据)

@CacheEvict(value = {"category"} , allEntries = true)

@Caching 【批量操作】

@Caching(evict = {
        @CacheEvict(value = {"category"} , key = "'getLevel1Categorys'"),
        @CacheEvict(value = {"category"} , key = "'getDataFromDb'")
})
@Transactional
@Override
public void updateCascade(CategoryEntity category) {
    this.updateById(category);
    categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
}

自定义缓存注解【可能是spring cache的简单实现】

定义注解

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cache {

    long expire() default 1*60*1000;

    // 缓存标志 key
    String name() default "";
}

注解aop实现

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;

//aop 定义一个切面,切面定义了切点和通知的关系
@Aspect
@Component
@Slf4j
public class CacheAspect {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Pointcut("@annotation(com.xxxx.blog.common.cache.Cache)")
    public void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp){
        try {
            Signature signature = pjp.getSignature();
            //类名
            String className = pjp.getTarget().getClass().getSimpleName();
            //调用的方法名
            String methodName = signature.getName();

            Class[] parameterTypes = new Class[pjp.getArgs().length];
            Object[] args = pjp.getArgs();
            //参数
            String params = "";
            for(int i=0; i<args.length; i++) {
                if(args[i] != null) {
                    params += JSON.toJSONString(args[i]);
                    parameterTypes[i] = args[i].getClass();
                }else {
                    parameterTypes[i] = null;
                }
            }
            if (StringUtils.isNotEmpty(params)) {
                //加密 以防出现key过长以及字符转义获取不到的情况
                params = DigestUtils.md5Hex(params);
            }
            Method method = pjp.getSignature().getDeclaringType().getMethod(methodName, parameterTypes);
            //获取Cache注解
            Cache annotation = method.getAnnotation(Cache.class);
            //缓存过期时间
            long expire = annotation.expire();
            //缓存名称
            String name = annotation.name();
            //先从redis获取
            String redisKey = name + "::" + className+"::"+methodName+"::"+params;
            String redisValue = redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isNotEmpty(redisValue)){
                log.info("走了缓存~~~,{},{}",className,methodName);
                Result result = JSON.parseObject(redisValue, Result.class);
                return result;
            }
            Object proceed = pjp.proceed();
            redisTemplate.opsForValue().set(redisKey,JSON.toJSONString(proceed), Duration.ofMillis(expire));
            log.info("存入缓存~~~ {},{}",className,methodName);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return Result.fail(-999,"系统错误");
    }

}

使用缓存

// redis缓存
@Cache(expire = 5 * 60 * 1000,name = "listArticle")
public Result listArticle(@RequestBody PageParams params){
    return articleService.listArticle(params);
}
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沛权

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值