前言

SpringBoot为我们自动配置了许多组件,当然缓存也是必不可少的。在SpringBoot中我们使用缓存只需要简单的写注解即可 这里我只讲讲如何使用 感兴趣的朋友可以看下源码 org.springframework.boot.autoconfigure.cache

 

1、使用

 

	/**
	*Cacheable属性
	*cacheNames/value:缓存组件名字CacheManager管理的多个Cache
	*key:Cache的key
	*keyGenerator:ket的生成器,可以自己定义key的id
	*cacheManager:指定缓存管理器
	*condition:指定条件符合条件在缓存
	*unless:否定缓存当unless指定的条件=true就不会缓存还可以根据结果进行缓存
	*sync:是否使用异步模式
	*
	*SpringcCache默认cachemanager是ConCurrentMapCacheManager 默认cache是ConCurrentMapCache
	*
	*过程:
	*默认使用方法参数的值作为key去从Cache中取没有就执行方法然后缓存有就直接返回缓存
	*@return
    */
    //查询全部
	@Cacheable(cacheNames="emps")
	public List<Employee> getAllEmp(String args){
	    return employeeMapper.selectByExample(null);
	}
	
	//按id查询
	@Cacheable(cacheNames="emps",key="#id",condition="#id>0")//id大于0才缓存j结果不为空才缓存
	    public Employee getEmpByid(Integer id){
	    return employeeMapper.selectByPrimaryKey(id);
	}
	
	//更新
	@CachePut(value="emps",key="#employee.id")//方法执行完成后更新emps中key为employee.id的数据
	public Employe eupdateByid(Employee employee){
	    employeeMapper.updateByPrimaryKey(employee);
	    return employee;
	}
	
	/**
	*方法执行后清除缓存key默认是参数
	*beforeInvocation:缓存清除是否在方法执行之前执行如=true如果当前方法出异常不管方法是否出错都会执行清除
	*@paramid
	*/
	//删除
	@CacheEvict(value="emps",key="#id"/*,allEntries=true*/)//allEntries=true*删除所有缓存
	public int delEmployee(Integerid){
	    int i = employeeMapper.deleteByPrimaryKey(id);
	    returni;
        }

@Caching

//指定多个cacheAble 和put、CacheEvict

SpringBoot从入门到精通04-Cache 

2、配置顺序加载

 SpringBoot从入门到精通04-Cache

 补充:

2、定义多个CacheManager时

@Parimary指定主要CacheManager

@Qualifier("xxxCacheManager")只使用这个CacheManager

 


 

相关文章: