springcloud redis 缓存使用注意事项

注意事项

1、@cacheput vs @cacheable 注解选择的问题

查看文章: @cacheput VS @cacheable: https://blog.csdn.net/Prepared/article/details/82699056

简单来说就是 update 的时候应该用 cacheput

2、同一个redis key的方法应该形成闭环。

就是说同一个 key 的方法,增删改查都应该添加缓存,当然查询不是必须的,但是加入缓存不就是为了查询更快嘛。

示例

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 

* 用户表 服务实现类 *

* * @author Heidi Zhou * @since 2018-06-03 */ @Service public class UserServiceImpl extends ServiceImpl implements UserService { private static final org.apache.log4j.Logger logger = Logger.getLogger(UserServiceImpl.class); /** * 找用户列表 * * @param page 分页对象 * @param wrapper 条件 * @return 用户列表 */ @Override public Page selectUser(Page page, Wrapper wrapper) { baseMapper.selectUser(page, wrapper); return page; } /**根据登录名返回用户对象*/ @Override public UserObject selectUserWithExtByLoginName(String policeNo) { UserObject userObject = baseMapper.selectUserWithExtByLoginName(policeNo); return userObject; } @Transactional(rollbackFor = Exception.class) @Cacheable(value = CacheConstant.CACHE_PERSON_PREFIX, key="#user.userid") @Override public User insertObject(User user){ baseMapper.insert(user); return user; } @CachePut(value = CacheConstant.CACHE_PERSON_PREFIX, key="#user.userid") @Transactional(rollbackFor = Exception.class) @Override public User update(User user) { baseMapper.updateById(user); return user; } @Transactional(rollbackFor = Exception.class) @Override @CacheEvict(value = CacheConstant.CACHE_PERSON_PREFIX, key="#user.userid") public boolean deleteById(User user) { return SqlHelper.delBool(baseMapper.deleteById(user.getUserid())); } @Transactional(rollbackFor = Exception.class) @Override @CacheEvict(value = CacheConstant.CACHE_PERSON_PREFIX) public boolean deleteBatchIds(List idList) { return SqlHelper.delBool(baseMapper.deleteBatchIds(idList)); } @Transactional(rollbackFor = Exception.class) @Override @CachePut(value = CacheConstant.CACHE_PERSON_PREFIX, key="#user.userid") public User update(User user, EntityWrapper ew) { baseMapper.update(user, ew); return user; } @Override public User selectOne(EntityWrapper ew) { return SqlHelper.getObject(baseMapper.selectList(ew)); } @Override @Cacheable(value = CacheConstant.CACHE_PERSON_PREFIX, key="#userId") public User selectById(String userId) { logger.info("+++++++++++++++++++++从数据库拿数据—+++++++++++++++++++++++"); return baseMapper.selectById(userId); } }

你可能感兴趣的:(java,微服务)