@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")用於標注在類上,可以存放該類中所有緩存的公有屬性,比如設置緩存的名字。