24、springboot与缓存(2)

具体看上文!!!

 

@Service
public class EmpService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Cacheable(cacheNames ="e")
    public Employee getEmp(Integer id){
        System.out.println("查询:" + id +"员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    @CachePut(value = "e")
    public Employee update(Employee employee){
        System.out.println("update。。。。");
        employeeMapper.updateEmp(employee);
        return employee;
    }
}

 

 

@ResponseBody
@RequestMapping("/emps")
public Employee update(Employee employee){
    Employee emp = empService.update(employee);
    return  emp;
}

 

 

@CachePut:即调用方法还更新数据
修改了数据库同时更新缓存
 
1.运行时机先调用目标方法
2.将目标方法保存
 
步骤:
1、查询1号员工,查到的结果会在缓存中
2、之后的查询还是之前的结果
3、更细员工
4、再次查询
    此时的结果时之前的结果
    1号员工没有在缓存中更新
    

 

此时测试流程:

 

 
此时的该标签需要拿到返回值,且它的名字value和cacheName相同

 

 

@CacheEvict:缓存清除
 
删除指定的key
@CacheEvict(value = "emp",key = "#id")
public void del(Integer id){
    System.out.println("del:"+ id);
    //employeeMapper.deleteEmpById(id);
}
@ResponseBody
@RequestMapping("/del")
public  String del(Integer id){
    empService.del(id);
    return  "success del ";
}

 

假设同时查询1,2两个员工,然后删除1,再去查2,依然不会调用数据库

 

@CacheEvict(value = "e",allEntries = true)
public void del(Integer id){
    System.out.println("del:"+ id);
    //employeeMapper.deleteEmpById(id);
}

 

假设同时查询1,2两个员工,然后删除1,再去查2,会调用数据库

 

 

@Caching() 定义复杂的缓存规则

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Caching {
    Cacheable[] cacheable() default {};
    CachePut[] put() default {};
    CacheEvict[] evict() default {};
}

 

 

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

 

 

EmpService.java

@Caching(
        cacheable = {
                @Cacheable(value = "emp",key = "#lastname")
        },
        put = {
                @CachePut(value = "emp",key = "#result.id"),
                @CachePut(value = "emp",key = "#result.email")
        }
)
//此时会将该数据的id、email、lastname数据都加载缓存中
public Employee getByName(String  lastname){
    return  employeeMapper.getEmpByLastName(lastname);
}

 

此时可以将lastname、id、email都可以查询的到

 

controller.java

@ResponseBody
@RequestMapping("/caching/lastname/{lastname}")
public Employee Cachings(@PathVariable("lastname") String lastname){
    Employee emp = empService.getByName(lastname);
    return emp;
}

 

 

此时查询id=2的用户依然会在缓存中进行查询

控制台并没有进行打印。

 

 

@CacheConfig 缓存注解配置类,此时可以指定所有所有的value等属性,不需要手动多次写

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheConfig {
    String[] cacheNames() default {};

    String keyGenerator() default "";

    String cacheManager() default "";

    String cacheResolver() default "";
}

 

posted @ 2019-02-26 09:21  MrChengs  阅读(256)  评论(0编辑  收藏  举报