资源管理模块集成Spring Cache
缓存同步的思路:
- 查询的时候添加到缓存中
- 增删改的时候,删除缓存
@Service @Transactional public class ResourceServiceImpl implements ResourceService { /** * 多条件列表查询 * @param resourceDto * @return */ @Cacheable(value = CacheConstant.RESOURCE_LIST ,key ="#resourceDto.hashCode()") @Override public List<ResourceVo> getList(ResourceDto resourceDto) { } /** * 封装资源的树形结构 * * @param resourceDto * @return */ @Cacheable(value = CacheConstant.RESOURCE_TREE ) @Override public TreeVo resourceTreeVo(ResourceDto resourceDto) { } /** * 添加资源 * @param resourceDto */ @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST ,allEntries = true), @CacheEvict(value = CacheConstant.RESOURCE_TREE ,allEntries = true)}) @Override public void createResource(ResourceDto resourceDto) { } /** * 修改资源 * @param resourceDto */ @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST ,allEntries = true), @CacheEvict(value = CacheConstant.RESOURCE_TREE ,allEntries = true)}) @Override public void updateResource(ResourceDto resourceDto) { } /** * 启用禁用 * @param resourceVo * @return */ @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST ,allEntries = true), @CacheEvict(value = CacheConstant.RESOURCE_TREE ,allEntries = true)}) @Override public void isEnable(ResourceVo resourceVo) { } /** * 删除菜单 * @param resourceNo */ @Caching(evict = {@CacheEvict(value = CacheConstant.RESOURCE_LIST ,allEntries = true), @CacheEvict(value = CacheConstant.RESOURCE_TREE ,allEntries = true)}) @Override public void deleteByResourceNo(String resourceNo) { } }
上述代码中使用到的常量需要自己定义:
package com.zzyl.constant; public class CacheConstant { /** * 缓存父包 */ public static final String RESOURCE_PREFIX= "resource:"; public static final String RESOURCE_LIST = RESOURCE_PREFIX+"list"; public static final String RESOURCE_TREE = RESOURCE_PREFIX+"tree"; }
其中ResourceDto 需要添加根据查询条件获取hashCode方法
@Override public int hashCode() { int result = Objects.hash(super.hashCode(), getParentResourceNo(), getResourceType(),getDataState()); return result; }
利用RedisTemplate代码的方式来实现缓存效果
public ResponseResult list(ResourceDto dto) { //查询redis String listStr = redisTemplate.opsForValue().get(CacheConstant.RESOURCE_LIST); //如果redis中有数据,则直接返回 if (StringUtils.isNotEmpty(listStr)) { //把字符串转成集合 List<Resource> resourceList = JSONArray.parseArray(listStr, Resource.class); return ResponseResult.success(resourceList); } //表示redis中没有命中 List<Resource> list = resourceMapper.list(dto); //同步数据到redis中一份 redisTemplate.opsForValue().set(CacheConstant.RESOURCE_LIST, JSON.toJSONString(list)); return ResponseResult.success(list); }