引入依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
緩存註解
- Cache:
緩存接口,定義緩存,實現包括:RedisCache,EhCacheCache,ConcurrentMapCache - CacheManager:
緩存管理器,管理各種緩存(Cache)組件 - @Cacheable:
針對方法配置,能夠根據方法的請求參數,對其結果進行緩存。 - @CacheEvict:
清空緩存
// @CacheEvict:緩存清除
// key:指定要清除的數據
// allEntries = true : 指定清除這個緩存中的所有數據
// beforeInvocation=fales: 緩存的清除是否在方法之前執行
// 默認代表緩存清除操作是在方法執行之後執行;如果出現異常緩存就不會清除
// beforeInvocation=true 代表清除緩存操作是在方法運行之前執行,無論方法是否出現異常,緩存都清除
@CacheEvict(beforeInvocation = true)
- @CachePut:
保證方法被調用,又希望結果被緩存。既調用方法,又更新緩存數據;同步更新緩存,修改了數據庫的某個數據,同時更新緩存
// 運行:
// 1.先調用目標方法
// 2.將目標方法的結果緩存起來 - @EnableCacheing:
開啓基於緩存的註解 - keyGenerator:
緩存數據時key生成策略 - serialize:
緩存數據時value序列化策略
/**
* @Caching是 @Cacheable、@CachePut、@CacheEvict註解的組合
* 以下註解的含義:
* 1.當使用指定名字查詢數據庫後,數據保存到緩存
* 2.現在使用id、age就會直接查詢緩存,而不是查詢數據庫
*/
@Caching(
cacheable = {@Cacheable(value = "person",key="#name")},
put={ @CachePut(value = "person",key = "#result.id"),
@CachePut(value = "person",key = "#result.age")
}
)
@Cacheable,@CachePut,@CacheEvict主要的配置參數:
- @Cacheable(value = {“user”})
value: 緩存的名稱,在spring配置文件中的定義,必須指定至少一個。 - @Cacheable(value = {“user”},key = “#user”)
key: 緩存的key ,非必填,指定需按照SpEL表達式編寫, 不指定,則缺省按照方法的所有參數進行組合 - @Cacheable(value = {“user”},condition = “#username.length()>8”)
condition: 緩存的條件,可以爲空, 可以爲SpEL編寫,返回true/false,在調用方法之前之後都螚判斷,只有爲true 才能進行緩存/清空緩存。 - @CacheEvict(value = “user”,allEntries = true)
allEntries: 是否清空緩存,默認爲false, 指定爲true, 方法調用後,立即清空所有緩存。 - @CacheEvict(value = “user”,beforeInvocation = true)
beforeInvocation: 是否在方法執行前清空,默認false, 指定爲true 在方法還沒執行的時候就清空緩存。 默認情況下,若方法執行拋出異常,則不會清空緩存。 - @Cacheable(value = “user”,unless = “#user==null”)
@CachePut(value = “user”,unless = “#user= =null”)
unless: 用於否決緩存,不像 condition
該表達式只在方法執行之後判斷,此時可以拿到返回值result 進行判斷, 條件爲true 不會緩存,false 纔會緩存。
主類:
開啓緩存註解
@SpringBootApplication
@EnableCaching
@MapperScan(basePackages = "com.feifan.mapper")
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class);
}
}
Service層
@Service
public class UserServiceImpl implements IUserService{
@Autowired
private UserDao userDao;
@Override
public UserDO findOne(int id) {
return userDao.findOne(id);
}
@Override
@Cacheable(cacheNames = {"find"})
public List<UserDO> findList(List<Integer> ids) {
System.err.println(">>>");
return userDao.findList(ids);
}
}
存入緩存,後面不進行查庫操作。
@Cacheables 能夠根據方法的請求參數對其結果進行緩存。
cacheNames 緩存的名稱,也就是在緩存中有一個叫emp的名字來標識不同的緩存組件。