Spring 3.1引入了基于注解(annotation)的缓存(cache)技术,它本质不是一个具体的缓存实现方案,而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的个助攻annotation,就能够达到缓存方法的返回对象的效果。

特点

  具备相当好的灵活性,不仅能够使用SpEL来定义缓存的key和各种condition,还提供开箱即用的缓存临时存储方案,也支持和主流的专业缓存例如EHCache、Redis、Guava的集成。

    基于annotation即可使得现有代码支持缓存

    开箱即用Out-Of-The-Box,不用安装和部署额外第三方组件即可使用缓存

    支持Spring Express Language,能使用对象的任何属性或者方法来定义缓存的key和condition

    支持AspectJ,并通过其实现任何方法的缓存支持

    支持自定义key和自定义缓存管理者,具有相当的灵活性和扩展性

使用前后

  使用前:

    我们需要硬编码,如果切换Cache Client还需要修改代码,耦合度高,不易于维护

  1. public String get(String key) {
  2. String value = userMapper.selectById(key);
  3. if (value != null) {
  4. cache.put(key,value);
  5. }
  6. return value;
  7. }

  使用后:

    基于Spring Cache注解,缓存由开发者自己配置,但不用参与到具体编码

  1. @Cacheable(value = "user", key = "#key")
  2. public String get(String key) {
  3. return userMapper.selectById(key);
  4. }

添加依赖

需要添加redis的依赖 同上篇

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.apache.commons</groupId>
  7. <artifactId>commons-pool2</artifactId>
  8. </dependency>

属性配置

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/david2018_db?characterEncoding=utf8
  4. username: root
  5. password: 1234
  6. redis:
  7. host: 10.211.55.5 #redis服务器地址
  8. timeout: 10000 #超时时间
  9. database: 0 #0-15 16个库 默认0
  10. lettuce:
  11. pool:
  12. max-active: 8 #最大连接数
  13. max-wait: -1 #默认-1 最大连接阻塞等待时间
  14. max-idle: 8 #最大空闲连接 默认8
  15. min-idle: 0 #最小空闲连接
  16. cache:
  17. type: redis

spring.cache.type 一般来说是根据依赖的包自行装配,但先后顺序会对redis使用有影响,(Jcache->EhCache->Redis->Guava) 最好还是手动配置一下

实体类

  1. public class t_user implements Serializable {
  2. private Integer id;
  3. private String username;
  4. private String password;
  5.  
  6. ...
  7. }

mybatisDao

  1. @Mapper
  2. public interface tUserDao {
  3. @Delete("delete from t_user where id = #{id}")
  4. int delete(int id);
  5.  
  6. @Update("update t_user set username = #{username},password = #{password} where id = #{id}")
  7. int update(t_user user);
  8.  
  9. @Select("select * from t_user where id = #{id}")
  10. t_user getById(int id);
  11. }

Service

  1. @Service
  2. public class t_userService {
  3.  
  4. @Resource
  5. private tUserDao dao;
  6.  
  7. @Cacheable(value="t_user",key="#id")
  8. public t_user getById(int id) {
  9. System.out.println("进入查询方法");
  10. return dao.getById(id);
  11. }
  12.  
  13. @CacheEvict(value="t_user",key="#id")
  14. public int delete(Integer id){
  15. System.out.println("进入删除方法");
  16. return dao.delete(id);
  17. }
  18.  
  19. @CachePut(value="t_user",key="#user.id")
  20. public int update(t_user user) {
  21. System.out.println("进入修改方法");
  22. return dao.update(user);
  23. }
  24. }

Controller

  1. @RequestMapping("/t_user")
  2. @RestController
  3. public class t_userController {
  4. @Autowired
  5. private t_userService service;
  6.  
  7. @GetMapping("/delete")
  8. public String delete(int id){
  9. service.delete(id);
  10. return "delete";
  11. }
  12.  
  13. @GetMapping("/update")
  14. public String update(t_user user){
  15. service.update(user);
  16. return "update";
  17. }
  18.  
  19. @GetMapping("/getById")
  20. public String getById(int id){
  21. return service.getById(id).toString();
  22. }
  23. }

最后在启动类中使用@EnableCaching启动Cache

  1. @EnableCaching
  2. @SpringBootApplication
  3. public class BootApplication{
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(BootApplication.class,args);
  7. }
  8. }

运行测试:http://localhost:8088/t_user/getById?id=1 输入此路径后 控制台只打印一次进入查询方法 说明缓存了 ,而修改 删除是回打印 修改了方法 和删除了的方法的,从而切面去删掉redis中缓存的数据。其中#代表是一个SpEL表达式。

根据条件操作缓存

  根据条件操作好uancun内容并不影响数据库操作,条件表达式返回一个布尔值,true/false,当条件为true,则进行缓存操作,否则直接调用方法返回结果。

    长度:@CachePut(value="user",key="#user.id",condition="#user.username.legnth() < 10") 只缓存用户名长度小于10的数据

    大小:@Cacheable(value="user",key="#id",condition="#id < 10") 只缓存id小于10的数据

    组合:@Cacheable(value="user",key="#user.username.concat(#user.password)")

    提前操作:@CacheEvict(value="user",allEntries=true,beforeInvocation=true)加上beforeInvocation=true后,不管内部是否报错,缓存都将被清除,默认情况为false。

注解介绍

  @Cacheable(根据方法的请求参数对其结果进行缓存)

    key:缓存的key,可以为空,如果指定要按照SpEL表达式编写,如果不指定,则缺省按照方法的所有参数进行组合(如:@Cacheable(value="user",key="#username"))

    value:缓存的名称,在Spring 配置文件中定义,必须指定至少一个(如:@Cacheable(value="user")或者@Cacheable(value={"user1","user2"})

    condition:缓存的条件,可以为空,使用SpEL编写,返回true或者false,只有为true才进行缓存(如:@Cacheable(value="user",key="#id",condition="#id < 10"))

  @CachePut(根据方法的请求参数对其结果进行缓存,和@Cacheable不同的是,它每次都会触发真实方法的调用)

  @CacheEvict(根据条件对缓存进行清空)

    allEntries:是否清空所有缓存内容,缺省为false,如果指定为true,则方法调用后将立即清空所有缓存(如:@CacheEvict(value="user",key="#id",allEntries=true))

    beforeInvocation:是否在方法执行前就清空,缺省为false,如果指定为true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法抛出异常,则不会清空缓存(如:@CacheEvict(value="user",key="#id",beforeInvocation))

Spring Boot (24) 使用Spring Cache集成Redis的更多相关文章

  1. Spring Boot 2.0 图文教程 | 集成邮件发送功能

    文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...

  2. Spring Boot 2.0 教程 | 快速集成整合消息中间件 Kafka

    欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...

  3. Spring Boot 2.X(二):集成 MyBatis 数据层开发

    MyBatis 简介 概述 MyBatis 是一款优秀的持久层框架,支持定制化 SQL.存储过程以及高级映射.它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简 ...

  4. Spring Boot——开发新一代Spring应用

    Spring官方网站本身使用Spring框架开发,随着功能以及业务逻辑的日益复杂,应用伴随着大量的XML配置文件以及复杂的Bean依赖关系.随着Spring 3.0的发布,Spring IO团队逐渐开 ...

  5. 使用 Spring Boot 快速构建 Spring 框架应用--转

    原文地址:https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/ Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2 ...

  6. 使用 Spring Boot 快速构建 Spring 框架应用,PropertyPlaceholderConfigurer

    Spring 框架对于很多 Java 开发人员来说都不陌生.自从 2002 年发布以来,Spring 框架已经成为企业应用开发领域非常流行的基础框架.有大量的企业应用基于 Spring 框架来开发.S ...

  7. Spring Boot中使用 Spring Security 构建权限系统

    Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...

  8. Spring Boot(十三):spring boot小技巧

    Spring Boot(十三):spring boot小技巧 一.初始化数据 我们在做测试的时候经常需要初始化导入一些数据,如何来处理呢?会有两种选择,一种是使用Jpa,另外一种是Spring JDB ...

  9. spring boot 打包方式 spring boot 整合mybaits REST services

    <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugi ...

随机推荐

  1. Divide Groups 二分图的判定

    Divide Groups Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Tot ...

  2. 基于XML文档的声明式事务配置

    <!-- 配置事务切面 --> <aop:config> <aop:pointcut expression="execution(* com.atguigu.t ...

  3. Leetcode 131.分割回文串

    分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab" 输出: [ ["aa" ...

  4. MongoDB 数据文件备份与恢复

    备份与恢复数据对于管理任何数据存储系统来说都是非常重要的. 1.冷备份与恢复——创建数据文件的副本(前提是要停止MongoDB服务器),也就是直接copy MongoDB将所有数据都存储在数据目录下, ...

  5. java并发操作

    项目中常用的java并发操作 一.java8新特性java并发流操作(结合纳姆达表达式) List<String> list = new ArrayList<>(); list ...

  6. Java发送带附件的QQ邮箱

    由于腾讯公司给QQ邮箱增加了一个授权码的密码保护,导致之前网上很多代码都不能用,于是就自己敲了一份demo. 注意在密码那里可能需要授权码,具体设置:http://service.mail.qq.co ...

  7. BZOJ(3) 1051: [HAOI2006]受欢迎的牛

    1051: [HAOI2006]受欢迎的牛 Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 7365  Solved: 3937[Submit][Sta ...

  8. 第5章 Cisco测试命令和TCP/IP连接故障处理

    第5章 Cisco测试命令和TCP/IP连接故障处理 一.故障处理命令 1.show命令: 1) 全局命令: show version :显示系统硬件和软件版本.DRAM.Flash show sta ...

  9. Java中的equals()和hashCode()

    概述 在我们使用类集框架(比方使用hashMap.hashSet)的时候,常常会涉及到重写equals()和hashCode()这两个方法. 这两个方法的联系是: 1. 假设两个对象不同,那么他们的h ...

  10. 【独立开发人员er Cocos2d-x实战 009】Cocos2dx 菜单项CCMenu使用

    Cocos2dx中的菜单用CCMenu/Menu类来实现.该类是一个容器.用来装载各种菜单项,用于菜单项能够是图片.系统字体等. 理论就不说了.先上代码: CCMenuItemToggle* item ...