当前位置: 首页 > 编程笔记 >

Spring Boot设置并使用缓存的步骤

鲜于德业
2023-03-14
本文向大家介绍Spring Boot设置并使用缓存的步骤,包括了Spring Boot设置并使用缓存的步骤的使用技巧和注意事项,需要的朋友参考一下

几个缓存注解的作用:

@Cacheable:将方法的返回结果根据key指定的键保存在缓存中,以后要获取相同的数据直接从缓存中共获取

  • cacheNames/value:指定Cache组件名称
  • key:指定缓存时使用的key,默认使用方法参数值,可以使用#a0、#p0、#参数名等,支持SpEL表达式,root可省略
  • keyGenerator:指定key的生成器的组件id,如自定义的KeyGenerator
  • cacheManager:指定缓存管理器
  • cacheResolver:指定缓存解析器
  • condition:指定在哪种条件下缓存,如condition = “#id>=1”在参数>=1时缓存
  • unless:指定该条件为真时不缓存
  • sync:指定是否使用异步模式

@CachePut:不管缓存中是否有需要的数据,都会执行该注解标注的方法,并将结果更新到缓存,属性见上

@CacheEvit:执行方法后,清除key指定的缓存

  • allEntries:默认为false,值为true,删除所有缓存
  • beforeInvocation:默认为false,值为true,在方法调用之前清除缓存

@CacheConfig:定义一些通用或公共的规则,如cacheNames、keyGenerator等

可使用的SpEL表达式:

使用缓存的步骤:

(1)创建一个Spring Boot应用,勾选Cache、Web、MySQL、Mybatis模块,在主程序类上添加注解,开启基于注解的缓存

@MapperScan(basePackages = "com.youngpain.cache.mapper")
@SpringBootApplication
@EnableCaching

(2)创建JavaBean,和数据库中的表对应,并配置数据源

spring:
 datasource:
  url: jdbc:mysql://localhost:3306/mybatis_database
  username: root
  password: 1741248769
  driver-class-name: com.mysql.jdbc.Driver
 redis:
  host: 39.108.114.57
#开启驼峰命名法
mybatis:
 configuration:
  map-underscore-to-camel-case: true
logging:
 level:
  com.youngpain.cache.mapper: debug

(3)创建mapper接口进行增删改查操作

/**
 * 部门表的增删改查操作
 */
public interface DepartmentMapper {
  @Insert("insert into department(id,depart_name,depart_build) values(#{id},#{depart_name},#{depart_build})")
  void insertDepartment(Department department);
  @Delete("delete from department where id=#{id}")
  void deleteDepartment(Integer id);
  @Update("update department set depart_name=#{departName},depart_build=#{departBuild} where id=#{id}")
  void updateDepartment(Department department);
  @Select("select * from department where id=#{id}")
  Department getDepartmentById(Integer id);
}

(4)创建service

@Service
@CacheConfig(cacheNames = {"departs"})
public class DepartmentService {
  @Autowired
  DepartmentMapper departmentMapper;
  @Cacheable(key = "#a0.id")
  public void insertDepartment(Department department) {
    departmentMapper.insertDepartment(department);
  }
  @CacheEvict(key = "#p0")
  public void deleteDepartment(Integer id) {
    departmentMapper.deleteDepartment(id);
  }
  @CachePut(key = "#a0.id")
  public Department updateDepartment(Department department) {
    departmentMapper.updateDepartment(department);
    return department;
  }
  @Cacheable(key = "#id", condition = "#p0>=1")
  public Department getDepartmentById(Integer id) {
    return departmentMapper.getDepartmentById(id);
  }
}

(5)创建controller

@Controller
public class DepartmentController {
  @Autowired
  DepartmentService departmentService;
  @GetMapping("/index")
  public String index() {
    return "index";
  }
  @GetMapping("/deleteDepart/{id}")
  public String deleteDepart(@PathVariable("id") Integer id, Model model) {
    model.addAttribute("condition", "delete");
    Department delete = departmentService.getDepartmentById(id);
    model.addAttribute("department", delete);
    departmentService.deleteDepartment(id);
    return "success";
  }
  @PostMapping("/updateDepart")
  public String updateDepart(Department department, Model model) {
    model.addAttribute("condition", "update");
    Department update = departmentService.updateDepartment(department);
    model.addAttribute("department", update);
    return "success";
  }
  @GetMapping("/getDepart/{id}")
  public String getDepartmentById(@PathVariable("id") Integer id, Model model) {
    model.addAttribute("condition", "delete");
    Department get = departmentService.getDepartmentById(id);
    model.addAttribute("department", get);
    return "success";
  }
}

(6)测试结果:

@Cacheable:第一次查询数据,控制台发出sql语句,之后再查询直接从缓存中获取
@CachePut:调用方法修改某个数据后,再次查询该数据是从缓存中获取的更新后的数据
@CacheEvict:调用该方法后,再次查询某个数据需要重新发出sql语句查询

ps:之前只是用markdown记笔记,今天第一次用markdown写文章,写起来好舒服啊QAQ

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对小牛知识库的支持。如果你想了解更多相关内容请查看下面相关链接

 类似资料:
  • 本文向大家介绍SpringBoot项目中使用redis缓存的方法步骤,包括了SpringBoot项目中使用redis缓存的方法步骤的使用技巧和注意事项,需要的朋友参考一下 本文介绍了SpringBoot项目中使用redis缓存的方法步骤,分享给大家,具体如下: Spring Data Redis为我们封装了Redis客户端的各种操作,简化使用。 - 当Redis当做数据库或者消息队列来操作时,我们

  • 本文向大家介绍SpringBoot下Mybatis的缓存的实现步骤,包括了SpringBoot下Mybatis的缓存的实现步骤的使用技巧和注意事项,需要的朋友参考一下 说起 mybatis,作为 Java 程序员应该是无人不知,它是常用的数据库访问框架。与 Spring 和 Struts 组成了 Java Web 开发的三剑客--- SSM。当然随着 Spring Boot 的发展,现在越来越多的

  • set 设置普通类型的值 设置 set set(key: string, value: string expiryMode: string[ EX 秒 PX 分钟 ], time: number ) key: 键名称 value:存储的值 expiryMode:添加过期时间类型 EX 秒 PX 分钟 time:过期时间 // 存储一个key为gender,value 为 男人的数据,10秒后过期

  • 我试图设置本地DynamoDB实例与SpringBoot。我跟着这个,但是格拉德尔。 当我尝试运行我的应用程序时,会出现以下异常: 我知道这是由于歧义导致的依赖注入失败,但我的是一个无参数构造函数。不确定歧义在哪里。 以下是我的代码: 格雷德尔锉刀 发电机配置 代理(实体) @DynamoDBTable(tableName="Agent")公共类Agent{私有字符串代理号;私有整数id;私有企业

  • 使用Spring的缓存抽象,如何让缓存异步刷新条目,同时仍返回旧条目? 我试图使用Spring的缓存抽象来创建一个缓存系统,在相对较短的“软”超时之后,缓存条目可以刷新。然后,当查询它们时,返回缓存的值,并启动异步更新操作来刷新条目。我也会 Guava的缓存生成器允许我指定缓存中的条目应该在一定时间后刷新。然后可以用异步实现覆盖缓存加载器的reload()方法,允许返回陈旧的缓存值,直到检索到新值

  • 本文向大家介绍SpringBoot使用Redis缓存的实现方法,包括了SpringBoot使用Redis缓存的实现方法的使用技巧和注意事项,需要的朋友参考一下 (1)pom.xml引入jar包,如下:   (2)修改项目启动类,增加注解@EnableCaching,开启缓存功能,如下:   (3)application.properties中配置Redis连接信息,如下:   (4)新建Redis