当前位置: 首页 > news >正文

SpringCache的介绍和使用

1.简介

1)Spring 从 3.1 开始定义了 org.springframework.cache.Cache和 org.springframework.cache.CacheManager 接口来统一不同的缓存技术;
并支持使用 JCache(JSR-107)注解简化我们开发;

2)每次调用需要缓存功能的方法时,Spring 会检查检查指定参数的指定的目标方法是否已
经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓
存结果后返回给用户。下次调用直接从缓存中获取。

这些介绍,大家看看就行了,我们主要如何使用它

2.基本概念图

3.常用注解

@EnableCaching:主方法中标注,表示开启缓存注解功能

@Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

@CachePut:也是将方法的返回结果放入到缓存中,和 @Cacheable 不同的是,它每次都会触发真实方法的调用,这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。

@CacheEvict:删除缓存

@Caching:组合以上多个操作的

4.使用

1)导入依赖

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

2)相关配置

application.properties

spring.cache.type=redis

#spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000

#如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true

#是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

 MyCachingConfig:

/**
 * springcach配置
 */
@EnableConfigurationProperties(CacheProperties.class)
@Configuration
public class MyCacheConfig {

//    @Autowired
//    CacheProperties cacheProperties;

    /**
     * 需要将配置文件中的配置设置上
     * 1、使配置类生效
     * 1)开启配置类与属性绑定功能EnableConfigurationProperties
     *
     * @ConfigurationProperties(prefix = "spring.cache")  public class CacheProperties
     * 2)注入就可以使用了
     * @Autowired CacheProperties cacheProperties;
     * 3)直接在方法参数上加入属性参数redisCacheConfiguration(CacheProperties redisProperties)
     * 自动从IOC容器中找
     * <p>
     * 2、给config设置上
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        // 当自己往IOC注入了RedisCacheConfiguration配置类时,以下参数全都失效,需要手动设置
        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;
    }
}

@EnableCaching:

 @Cacheable


    /**
     *  key是默认生成的:缓存的名字::SimpleKey::[](自动生成key值)
     *  缓存的value值,默认使用jdk序列化机制,将序列化的数据存到redis中
     *  默认时间是 -1
     * @return
     *    自定义操作:key的生成
     *  1. 指定生成缓存的key:key属性指定,接收一个 SpEl,关于SpEl的写法,可以查看Cacheable注解的注释或官方文档,
     *  2. 指定缓存的数据的存活时间:配置文档中修改存活时间 ttl (配置文件已设置)
     *  3. 将数据保存为json格式: 自定义配置类 MyCacheManager (配置文件已设置)
     *  4.如果key想要设置为字符需要这样写:key=”‘内容’“
     *  5.下面的category是分区名(就是有很多种类的缓存,比如品牌的,分类的等)
     *  6.下面的key是缓存的名字
     */
    @Cacheable(value ="category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        List<CategoryEntity> list = this.list(null);
        //查出一级菜单
        List<CategoryEntity> categorys = this.list(new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        Map<String, List<Catelog2Vo>> collect1 = categorys.stream().collect(Collectors.toMap((k) -> {
            return k.getCatId().toString();
        }, (v) -> {
            List<CategoryEntity> categoryEntity2 = getParent_cid(list, v.getCatId());
            List<Catelog2Vo> catelog2Vos = categoryEntity2.stream().map((obj) -> {
                Catelog2Vo catelog2Vo = new Catelog2Vo();
                catelog2Vo.setCatalog1Id(v.getCatId().toString());
                catelog2Vo.setId(obj.getCatId().toString());
                catelog2Vo.setName(obj.getName());
                List<CategoryEntity> catelog3Vo = getParent_cid(list, obj.getParentCid());
                List<Catelog2Vo.Catalog3Vo> collect = catelog3Vo.stream().map((vo3) -> {
                    Catelog2Vo.Catalog3Vo catelo3Vo = new Catelog2Vo.Catalog3Vo();
                    catelo3Vo.setName(vo3.getName());
                    catelo3Vo.setId(vo3.getCatId().toString());
                    catelo3Vo.setCatalog2Id(obj.getCatId().toString());
                    return catelo3Vo;
                }).collect(Collectors.toList());
                catelog2Vo.setCatalog3List(collect);
                return catelog2Vo;
            }).collect(Collectors.toList());
            return catelog2Vos;
        }));
        return collect1;
    }

缓存结果:

CachePut:这个注解的使用和Cacheable的差不多,要注意他们的区别

@CacheEvict:删除category分区下的key为getCatalogJson,一般使用在修改方法,注意单引号

  @Caching

举个例子。我们要删除category分区下的key为one和key为two的两个key,怎么办呢?

第一种写法:

 第二种写法:注意这是删除category分区下的所有key

  希望对你有帮助,有问题私信一起交流!

相关文章:

  • java-php-python-ssm艾灸减肥管理网站计算机毕业设计
  • 力扣每日一题2022-09-23中等题:设计链表
  • 内存数据库简介-内存数据库性能排行
  • 【云原生】Hadoop on k8s 环境部署
  • 不同编码格式(Unicode、多字节字符)vs环境下使用printf、scanf应注意事项
  • 使用Express获取jquery数据 使用模块化 共享自己的数据库
  • Python算法:决策树分类
  • IDEA插件开发-学习
  • python工具方法35 实现SWA,再一次提升模型的性能
  • mysql查询优化实战:查询用时一分半降到三毫秒
  • 你用什么方法做副业赚钱?
  • 十五:Fiddler抓包教程(15)-Fiddler弱网测试
  • 【最长公共子序列】两行字符串,不交叉相连,最多连线
  • 终端I/O.
  • MySQL触发器简介
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • 【跃迁之路】【463天】刻意练习系列222(2018.05.14)
  • android图片蒙层
  • download使用浅析
  • ES6语法详解(一)
  • JavaScript服务器推送技术之 WebSocket
  • nginx(二):进阶配置介绍--rewrite用法,压缩,https虚拟主机等
  • Puppeteer:浏览器控制器
  • SwizzleMethod 黑魔法
  • webgl (原生)基础入门指南【一】
  • webpack4 一点通
  • 初识 beanstalkd
  • 诡异!React stopPropagation失灵
  • 技术胖1-4季视频复习— (看视频笔记)
  • 开源SQL-on-Hadoop系统一览
  • 设计模式 开闭原则
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 微信支付JSAPI,实测!终极方案
  • Java性能优化之JVM GC(垃圾回收机制)
  • Semaphore
  • ​Distil-Whisper:比Whisper快6倍,体积小50%的语音识别模型
  • ​Java并发新构件之Exchanger
  • ​中南建设2022年半年报“韧”字当头,经营性现金流持续为正​
  • ()、[]、{}、(())、[[]]等各种括号的使用
  • (175)FPGA门控时钟技术
  • (3)选择元素——(17)练习(Exercises)
  • (4)通过调用hadoop的java api实现本地文件上传到hadoop文件系统上
  • (9)YOLO-Pose:使用对象关键点相似性损失增强多人姿态估计的增强版YOLO
  • (poj1.2.1)1970(筛选法模拟)
  • (Redis使用系列) SpringBoot中Redis的RedisConfig 二
  • (动手学习深度学习)第13章 计算机视觉---微调
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (附源码)spring boot公选课在线选课系统 毕业设计 142011
  • (附源码)SSM环卫人员管理平台 计算机毕设36412
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (三)Hyperledger Fabric 1.1安装部署-chaincode测试
  • (转)C#调用WebService 基础
  • (转)IIS6 ASP 0251超过响应缓冲区限制错误的解决方法
  • (转)VC++中ondraw在什么时候调用的