package com.roncoo.example.cache.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Repository; import com.roncoo.example.bean.RoncooUserLog; import com.roncoo.example.cache.RoncooUserLogCache; import com.roncoo.example.dao.RoncooUserLogDao; /** * @author wei.liu */ @CacheConfig(cacheNames = "roncooCache") @Repository public class RoncooUserLogCacheImpl implements RoncooUserLogCache { @Autowired private RoncooUserLogDao roncooUserLogDao; @Cacheable(key = "#p0") @Override public RoncooUserLog selectById(Integer id) { System.out.println("查询功能,缓存找不到,直接读库, id=" + id); return roncooUserLogDao.findOne(id); } @CachePut(key = "#p0") @Override public RoncooUserLog updateById(RoncooUserLog roncooUserLog) { System.out.println("更新功能,更新缓存,直接写库, id=" + roncooUserLog); return roncooUserLogDao.save(roncooUserLog); } @CacheEvict(key = "#p0") @Override public String deleteById(Integer id) { System.out.println("删除功能,删除缓存,直接写库, id=" + id); return "清空缓存成功"; } }
一、@Cacheable:主要用来配置方法,可以根据方法的请求参数对其结果进行缓存。即当重复使用相同参数调用方法的时候,方法自己不会被调用执行,即方法自己被略过了,取而代之的是方法的结果直接从缓存中找到并返回了。spring
参数介绍:缓存
value:缓存的名字,必须指定至少一个。ide
key:缓存的key,能够为空,若是指定要按照SpEL表达式编写;若是不指定,则缺省按照方法的全部参数进行组合。code
condition:缓存的条件,能够为空,使用SpEL编写,返回true或者false,只有为true才能缓存。get
例子:it
@Cacheable(value="shops:detail",key="'id:'+#p0") public Shop getById(String id);
二、@CacheEvict:主要对方法配置,用来标记要清空缓存的方法,当这个方法被调用并知足必定条件后,即会清空缓存。io
参数解析:class
allEntries:true表示清除value中的所有缓存,默认为false。import
例子:配置
@CacheEvict(value="shops:detail",key="'id:'+#p0['id']",condition="#p0['id']>0") public Shop getById(Map<String, Object> param);
@Caching(evict={@CacheEvict(value="shops:brief",allEntries=true)}) public void delete(String id);
上面两行代码表示,只要执行了delete方法,就刷新缓存名为”shops:brief”下面的全部缓存。
三、@CachePut:主要针对方法的配置,可以根据方法的请求参数对其结果进行缓存,和@Cacheable不一样的是,它每次都会触发真实方法的调用。
@CachePut(value="shops:detail",key="'id:'+#p0['id']") public Shop update(Map<String, Object> param);
上面两行代码表示,当调用update方法时,该方法体会被执行,而且执行的结果会返回写入到缓存中。