Spring Boot与缓存:使用JCache(JSR-107)注解简化开发

Spring Boot与缓存:使用JCache(JSR-107)注解简化开发

JSR107

  • Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry。
  1. CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期访问多个CachingProvider。
  2. CacheManager定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于CacheManager的上下文中。一个CacheManager仅被一个CachingProvider所拥有。
  3. Cache是一个类似Map的数据结构并临时存储以Key为索引的值。一个Cache仅被一个CacheManager所拥有。
  4. Entry是一个存储在Cache中的key-value对。
  5. Expiry 每一个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期的状态。一旦过期,条目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。

在这里插入图片描述

Spring缓存抽象

  • Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化我们开发;
  • Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
  • Cache接口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache , ConcurrentMapCache等;
  • 每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。
  • 使用Spring缓存抽象时我们需要关注以下两点
  1. 确定方法需要被缓存以及他们的缓存策略
  2. 从缓存中读取之前缓存存储的数据

在这里插入图片描述

几个重要概念和缓存注解的使用

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

缓存的使用

  1. 引入spring-boot-starter-cache模块
  2. @EnableCaching开启缓存
  3. 使用缓存注解
  4. 切换为其他缓存

实体类、controller以及mapper的代码

  • 每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。
  • 缓存相关的代码主要在service的编写,这边先列出实体类、controller以及mapper的代码。重点分析service的代码。

实体类

  • 部门类
public class Department {	
	private Integer id;
	private String departmentName;
}
  • 员工类
public class Employee implements Serializable {
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender; //性别 1男  0女
	private Integer dId;
}

控制器controller

  • 部门控制器:查询指定员工id的部门信息
@RestController
public class DeptController {

    @Autowired
    DeptService deptService;

    @GetMapping("/dept/{id}")
    public Department getDept(@PathVariable("id") Integer id){
        return deptService.getDeptById(id);
    }
}
  • 员工控制器
@RestController
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;
//查询指定id的员工信息
    @GetMapping("/emp/{id}")
    public Employee getEmployee(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return employee;
    }
//更新员工
    @GetMapping("/emp")
    public Employee update(Employee employee){
        Employee emp = employeeService.updateEmp(employee);
        return emp;
    }
//删除员工
    @GetMapping("/delemp")
    public String deleteEmp(Integer id){
        employeeService.deleteEmp(id);
        return "success";
    }
//用lastname查询员工
    @GetMapping("/emp/lastname/{lastName}")
    public Employee getEmpByLastName(@PathVariable("lastName") String lastName){
       return employeeService.getEmpByLastName(lastName);
    }

}

Mapper

  • 部门mapper
@Mapper
public interface DepartmentMapper {

    @Select("SELECT * FROM department WHERE id = #{id}")
    Department getDeptById(Integer id);
}

  • 员工mapper
@Mapper
public interface EmployeeMapper {

    @Select("SELECT * FROM employee WHERE id = #{id}")
    public Employee getEmpById(Integer id);

    @Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
    public void updateEmp(Employee employee);

    @Delete("DELETE FROM employee WHERE id=#{id}")
    public void deleteEmpById(Integer id);

    @Insert("INSERT INTO employee(lastName,email,gender,d_id) VALUES(#{lastName},#{email},#{gender},#{dId})")
    public void insertEmployee(Employee employee);

    @Select("SELECT * FROM employee WHERE lastName = #{lastName}")
    Employee getEmpByLastName(String lastName);
}

代码分析

主程序@EnableCaching

  • @EnableCaching 开启缓存
  • @MapperScan指定需要扫描的mapper接口所在的包
@MapperScan("com.cache.mapper")
@SpringBootApplication
@EnableCaching
public class Springboot01CacheApplication {
	public static void main(String[] args) {
		SpringApplication.run(Springboot01CacheApplication.class, args);
	}
}

缓存的自动配置

  • 自动配置类: CacheAutoConfiguration
  • CacheAutoConfiguration缓存有如下配置类
    • org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
    • org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
    • org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
  • 默认生效的是配置类:SimpleCacheConfiguration,其他的配置类比如RedisCacheConfiguration如果要生效必须添加相关的Redis配置信息,否则默认不生效。
  • 原理
  1. 给容器中注册了一个CacheManager:ConcurrentMapCacheManager
  2. 可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
    默认使用的是ConcurrentMapCacheManager==ConcurrentMapCache;将数据保存在 ConcurrentMap<Object, Object>中

@Cacheable

  • @Cacheable注解工作原理:@Cacheable标注的方法在执行之前会先检查缓存中有没有这个数据,默认按照参数的值作为缓存的key去查询缓存,如果没有就运行该方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
  • @Cacheable详细工作流程
  1. 方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;(CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
  2. 去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
    SimpleKeyGenerator生成key的默认策略;
  • 如果没有参数;key=new SimpleKey();
  • 如果有一个参数:key=参数的值
  • 如果有多个参数:key=new SimpleKey(params);
  1. 没有查到缓存就调用目标方法;
  2. 将目标方法返回的结果,放进缓存中

将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法;
CacheManager管理多个Cache组件的,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字;

  • @Cacheable的几个属性
  1. cacheNames/value:指定缓存组件的名字;将方法的返回结果放在哪个缓存中,是数组的方式,可以指定多个缓存;
  2. key:缓存数据使用的key;可以用它来指定。默认是使用方法参数的值 1-方法的返回值
  • 编写SpEL; #id;参数id的值 #a0 #p0 #root.args[0]
  • getEmp[2]
  1. keyGenerator:key的生成器;可以自己指定key的生成器的组件id
    key/keyGenerator:二选一使用
  2. cacheManager:指定缓存管理器;或者cacheResolver指定获取解析器
  3. condition:指定符合条件的情况下才缓存;
  • condition = “#id>0”
  • condition = “#a0>1”:第一个参数的值大于1的时候才进行缓存
  1. unless:否定缓存;当unless指定的条件为true,方法的返回值就不会被缓存;可以获取到结果进行判断
  • unless = “#result == null”
  • unless = “#a0==2”:如果第一个参数的值是2,结果不缓存;
  1. sync:是否使用异步模式
代码

这里使用自定义的KeyGenerator:“myKeyGenerator”

    @Cacheable(value = {"emp"},keyGenerator = "myKeyGenerator",condition = "#a0>1",unless = "#a0==2")
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }
  • myKeyGenerator的定义写在配置类
  • 所以对应生成器生成的key值是:getEmp[id] 例如getEmp[0],getEmp[1]
@Configuration
public class MyCacheConfig {
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator(){
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString()+"]";
            }
        };
    }
}

@CachePut

  • @CachePut:既调用方法,又更新缓存数据;同步更新缓存
  • 应用场景:修改了数据库的某个数据,同时更新缓存;
  • 流程:
    1、先调用目标方法
    2、将目标方法的结果缓存起来
    @CachePut(value = "emp",key = "#result.id")
    public Employee updateEmp(Employee employee){
        System.out.println("updateEmp:"+employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }

@CacheEvict

  • @CacheEvict:缓存清除
  • key:指定要清除的数据
  • allEntries = true:指定清除这个缓存中所有的数据
  • beforeInvocation = false:缓存的清除是否在方法之前执行。默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除。
  • beforeInvocation = true:代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
    @CacheEvict(value="emp",beforeInvocation = true,key = "#id")
    public void deleteEmp(Integer id){
        System.out.println("deleteEmp:"+id);
        employeeMapper.deleteEmpById(id);
    }

@Caching

  • @Caching 综合上面介绍的几个注解,用来定义较为复杂的缓存规则
@Caching(
         cacheable = {
             @Cacheable(/*value="emp",*/key = "#lastName")
         },
         put = {
             @CachePut(/*value="emp",*/key = "#result.id"),
             @CachePut(/*value="emp",*/key = "#result.email")
         }
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值