SpringBoot 缓存
@Cacheable注解的介绍
Cacheable注解是Spring框 架中的缓存注解之一。该注解能够让方法的返回值被缓存起来,后续的请求可以直接从缓存中获取结果,从而减少了调用方法的次数,提高了系统的性能。
使用Cacheable注解实现简单的缓存
在编写一个使用缓存的方法时,只需要在需要被缓存的方法上加上@Cacheable注解,同时指定缓存的名称和缓存的key即可。当第一次调用被缓存的方法时,方法的返回值会被缓存起来,后续的请求会直接从缓存中获取结果。
/**
- 使用缓存的方法
- @param id 用户id
- @return 用户的姓名
*/
@Cacheable(value = “user”, key = “#id”)
public String getUserName(String id) {
// 从数据库或其他数据源获取用户名
String userName = getUserInfoFromDatabase(id);
return userName;
}
value : 缓存的名称
key: 缓存的键名 #id对就方法中的查询条件id,用于从缓存中获取数据
使用Cacheable注解实现缓存的过期
/**
* 使用缓存的方法,设置过期时间为1个小时
* @param id 用户id
* @return 用户的姓名
*/
@Cacheable(value = "user", key = "#id", expire = 3600)
public String getUserName(String id) {
// 从数据库或其他数据源获取用户名
String userName = getUserInfoFromDatabase(id);
return userName;
}
expire:缓存过期时间,以秒为单位。如果不指定expire属性,则该缓存将一直有效。
使用Cacheable注解实现条件缓存
/**
* 使用条件缓存方法
* @param id 用户id
* @param enabled 是否启用缓存
* @return 用户的姓名
*/
@Cacheable(value = "user", key = "#id", condition = "#enabled")
public String getUserNameWithCondition(String id, boolean enabled) {
// 从数据库或其他数据源获取用户名
String userName = getUserInfoFromDatabase(id);
return userName;
}
condition属性,该属性的含义为缓存条件。如果该条件为true,则缓存生效,否则不生效。
使用Cacheable注解实现自定义缓存
在某些情况下,我们可能需要自定义缓存。使用@Cacheable注解可以非常方便地实现自定义缓存。只需要实现Cache接口,重写put、get、evict和clear方法即可。
/**
* 支持自定义缓存的注解
* @param id 用户id
* @param cacheImpl 自定义的缓存实现类
* @return 用户的姓名
*/
@Cacheable(value = "user", key = "#id", cacheManager = "customCacheManager")
public String getUserNameWithCustomCache(String id, CustomCacheImpl cacheImpl) {
// 从数据库或其他数据源获取用户名
String userName = getUserInfoFromDatabase(id);
return userName;
}
/**
* 自定义的缓存实现类,实现Cache接口
*/
public class CustomCacheImpl implements Cache {
// 实现put、get、evict和clear方法
}