@Caching:用于定制复杂的缓存规则
package com.gong.springbootcache.controller; import com.gong.springbootcache.bean.Employee; import com.gong.springbootcache.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class EmployeeController { @Autowired EmployeeService employeeService; //value:指定缓存的名字,每个缓存组件有一个唯一的名字。缓存组件由CacheManager进行管理。 //key:缓存数据时用到的key,默认使用方法参数的值,1-方法返回值 key = //#id也可这么表示:#root.args[0](第一个参数) //keyGenerator:指定生成缓存的组件id,使用key或keyGenerator其中一个即可 //cacheManager,cacheResolver:指定交由哪个缓存管理器,使用其中一个参数即可 //condition:指定符合条件时才进行缓存 //unless:当unless指定的条件为true,方法的返回值就不会被缓存 //sync:是否使用异步模式 //"#root.methodName+'[+#id+]'" @Cacheable(value = "emp") @ResponseBody @RequestMapping("/emp/{id}") public Employee getEmp(@PathVariable("id") Integer id){ Employee emp = employeeService.getEmp(id); return emp; } @CachePut(value = "emp",key="#employee.id") @ResponseBody @GetMapping("/emp") public Employee updateEmp(Employee employee){ Employee emp = employeeService.updateEmp(employee); return emp; } @CacheEvict(value = "emp",key = "#id") @ResponseBody @GetMapping("/emp/del/{id}") public String deleteEmp(@PathVariable("id") Integer id){ //employeeService.deleteEmp(id); return "删除成功"; } @Caching( cacheable = { @Cacheable(value = "emp",key = "#lastName") }, put = { @CachePut(value = "emp",key = "#result.id"), @CachePut(value = "emp",key = "#result.email"), } ) @ResponseBody @RequestMapping("/emp/lastName/{lastName}") public Employee getEmpByLastName(@PathVariable("lastName") String lastName){ Employee employee = employeeService.getEmpByLastName(lastName); return employee; } }
在执行Localhost:8080/emp/lastName/jack请求之后,会同时将@CachePut缓存规则加入到缓存中。
@CacheConfig(cacheNames="emp")用于标注在类上,可以存放该类中所有缓存的公有属性,比如设置缓存的名字。