springbootii-cache 基于注解的声明式缓存

测试版本springboo2.0.4

 

1、使用缓存注解

通用属性解释:

value属性:要使用缓存的名称

key属性:使用SpEL表达式自定义缓存Key,

例如:#name—以参数name作为自定义缓存Key,

#result.name—以返回值结果的name属性作为自定义缓存Key

 

(1)@Cacheable注解

如果没有缓存则会执行方法并将返回值缓存,如果有缓存时,不会执行方法而是直接返回缓存中的值

 /**
     * cacheNames 设置缓存的值
     * key:指定缓存的key,这是指参数id值。key可以使用spEl表达式
     */
    @Cacheable(value = "userCache", key = "#id", unless="#result == null")
    public User getById(int id) {
        logger.info("获取用户start...");
        return userMapper.selectById(id);
    }

 

 

@Cacheable(value = "allUsersCache", unless = "#result.size() == 0")
    public List<User> getAllUsers() {
        logger.info("获取所有用户列表");
        return userMapper.selectList(null);
    }

当返回的结果size == 0时 不缓存

 

(2)@CachePut注解

不管有没有缓存都会执行方法并将结果缓存起来

 

(3)@CacheEvict注解

移除指定缓存

/**
     * 创建用户,同时使用新的返回值的替换缓存中的值
     * 创建用户后会将allUsersCache缓存全部清空
     */
    @Caching(
            put = {@CachePut(value = "userCache", key = "#user.id")},
            evict = {@CacheEvict(value = "allUsersCache", allEntries = true)}
    )
    public User createUser(User user) {
        logger.info("创建用户start..., user.id=" + user.getId());
        userMapper.insert(user);
        return user;
    }

 

创建一个新用户会缓存,然后清空掉所有用户的缓存

注意:

a.User对象需要实现序列化接口

b.只有@CacheEvict注解的方法返回值可以为void

 参考项目

 

 

参考:

https://my.oschina.net/u/3773384/blog/1795296

posted @ 2018-12-12 15:14  lyon♪♫  阅读(336)  评论(0编辑  收藏  举报