说明: 建议先阅读下列文章
SpringBoot 缓存之 @Cacheable 详细介绍
向数据库查询结果,如果不为NULL,就放入缓存中
/**
* 作家信息 缓存管理类
*
* @author xiongxiaoyang * @date 2022/5/12 */@Component
@RequiredArgsConstructor
public class AuthorInfoCacheManager {
private final AuthorInfoMapper authorInfoMapper;
/**
* 查询作家信息,并放入缓存中
*/
@Cacheable(cacheManager = CacheConsts.REDIS_CACHE_MANAGER,
value = CacheConsts.AUTHOR_INFO_CACHE_NAME, unless = "#result == null")
public AuthorInfoDto getAuthor(Long userId) {
QueryWrapper<AuthorInfo> queryWrapper = new QueryWrapper<>();
queryWrapper
.eq(DatabaseConsts.AuthorInfoTable.COLUMN_USER_ID, userId)
.last(DatabaseConsts.SqlEnum.LIMIT_1.getSql());
AuthorInfo authorInfo = authorInfoMapper.selectOne(queryWrapper);
if (Objects.isNull(authorInfo)) {
return null;
}
return AuthorInfoDto.builder()
.id(authorInfo.getId())
.penName(authorInfo.getPenName())
.status(authorInfo.getStatus()).build();
}
@CacheEvict(cacheManager = CacheConsts.REDIS_CACHE_MANAGER,
value = CacheConsts.AUTHOR_INFO_CACHE_NAME)
public void evictAuthorCache() {
// 调用此方法自动清除作家信息的缓存
}
}
关于AuthorInfoMapper直接继承MP的基类:
public interface AuthorInfoMapper extends BaseMapper<AuthorInfo> {
}
其它常量:
/**
* Redis 缓存管理器
*/
public static final String REDIS_CACHE_MANAGER = "redisCacheManager";
/**
* 作家信息缓存
*/
public static final String AUTHOR_INFO_CACHE_NAME = "authorInfoCache";
public static final String COLUMN_USER_ID = "user_id";
/**
* SQL语句枚举类
*/
@Getter
public enum SqlEnum {
LIMIT_1("limit 1"),
LIMIT_2("limit 2"),
LIMIT_5("limit 5"),
LIMIT_30("limit 30"),
LIMIT_500("limit 500");
private String sql;
SqlEnum(String sql) {
this.sql = sql;
}
}
service层调用
@Override
public RestResp<Integer> getStatus(Long userId) {
AuthorInfoDto author = authorInfoCacheManager.getAuthor(userId);
return Objects.isNull(author) ? RestResp.ok(null) : RestResp.ok(author.getStatus());
}
我们发现,我们在缓存管理器中调用了mapper层,而不是直接在service调用mapper,由此可见,相当于在service⇒mapper的中间加入缓存管理,然后service调用缓存管理器即可!在第三方动手脚!!!
关于缓存更多文章:
大厂都在用 EhCache,它到底比 Redis 强在哪里?