1.启动类中开启缓存
@SpringBootApplication
@EnableCaching //开启缓存
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
2.服务层定义缓存表示@CacheConfig
@CacheConfig(cacheNames = "user")表示此服务层缓存都为“user”命名
@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
3.数据缓存@Cacheable
缓存默认key值是参数id值
@Override
@Cacheable
public User getUserById(String id) {
System.out.println("####################################:"+id);
return userMapper.selectById(id);
}
3.缓存的更新@CachePut
key是更新后数据的id,更新的内容默认为返回的值
@Override
@CachePut(key = "#result.id")
@Transactional
public User updateUserById(User user) {
userMapper.updateById(user);
return userMapper.selectById(user.getId());
}
4.清楚缓存@CacheEvict
缓存默认key值是参数id值。beforeInvocation =true 表示删除用户的方法执行前清楚缓存
@Override
@CacheEvict(beforeInvocation = true)
public Integer DeleteUserById(String id) {
return userMapper.deleteById(id);
}
网友评论