Jetcache前言

因为之前项目的原因接触过jecache,但是没有好好整理,今天闲下来,悉心整理了下,并看了下文档,学了下自动刷新缓存,感觉这个挺适合用来更新首页轮播图,通栏的。

基本配置(Spring Boot)

配置

pom.xml
<!-- jetCache  -->
<dependency>
    <groupId>com.alicp.jetcache</groupId>
    <artifactId>jetcache-starter-redis</artifactId>
    <version>2.6.0</version>
</dependency>
application.yml
#jetcache
# @see com.alicp.jetcache.autoconfigure.JetCacheProperties
jetcache:
  # 统计间隔,默认0:表示不统计
  statIntervalMinutes: 1
  # areaName是否作为缓存key前缀,默认True
  areaInCacheName: false
  local:
    default:
      # 已支持可选:linkedhashmap、caffeine
      type: linkedhashmap
      # key转换器的全局配置,当前只有:fastjson, @see com.alicp.jetcache.support.FastjsonKeyConvertor
      keyConvertor: fastjson
      # 每个缓存实例的最大元素的全局配置,仅local类型的缓存需要指定
      limit: 100
      # jetcache2.2以上,以毫秒为单位,指定多长时间没有访问,就让缓存失效,当前只有本地缓存支持。0表示不使用这个功能,指定30秒后失效
      expireAfterAccessInMillis: 30000
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: ${redis.host}
      port: 6379
      password: ${redis.password}
启动类
@SpringBootApplication
@EnableMethodCache(basePackages = "com.company.mypackagee")
@EnableCreateCacheAnnotation
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

基本使用

  • 下面例子以操作User为例
    user.java

    @TableName(value = "user")
    @Data
    public class User implements Serializable {
        private static final long serialVersionUID = 738881519595997996L;
        /**主键**/
        @NotNull(message = "主键不能为空")
        private Long id;
        /**姓名**/
        @NotBlank(message = "名字不能为空")
        @Length(min = 1, message = "名字至少1个字")
        private String name;
        /**手机号**/
        @NotBlank(message = "手机号不能为空")
        @Size(max = 11, message = "手机号最长11位")
        @Pattern(regexp = "^1\\d+$", message = "手机号格式不正确")
        private String phone;
        /**电子邮件**/
        @NotBlank(message = "邮箱不能为空")
        @Email(message = "电子邮件格式不正确")
        @Length(max = 30, message = "邮箱长度不能超过30!")
        private String email;
        /**自我介绍**/
        private String aboutme;
        /**加密密码**/
        private String passwd;
        /**头像图片**/
        private String avatar;
        /**1:普通用户,2:房产经纪人**/
        private Integer type;
        /**创建时间**/
        private Date createTime;
        /**是否启用,1启用,0停用**/
        private Integer enable;
        /**所属经纪机构**/
        private Integer agencyId;
    }

基于注解实现方法缓存

@Cached:创建缓存
/**
 * 基于注解创建缓存
 * 缓存在 Remote 的 Redis,也可以配置成 both 开启两级缓存
 */
@Cached(name = CACHE_NAME, key = "#userId", cacheType = CacheType.LOCAL, expire = 5 * 60)
@CacheRefresh(refresh = 60)
public UserVO findUserById(Long userId) {
    User user = userMapper.selectOne(queryWrapper);
    //.....................
}
@CacheInvalidate:删除缓存
@CacheInvalidate(name = CACHE_NAME, key = "#userId")
@Transactional(rollbackFor = Exception.class)
public int deleteUserById(Long userId) {
    User user = new User();
    user.setId(userId);
    user.setEnable(0);
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.lambda().eq(User::getId, userId).eq(User::getEnable, 1);
    return userMapper.update(user, updateWrapper);
}
@CacheUpdate:更新缓存
/**
 * 更新用户
 * @param user 用户
 * @return int
 */
@CacheUpdate(name = CACHE_NAME, key = "#user.id", value = "#user")
public int updateUser(User user) {
    log.info("【UserUpdate操作】, user = {}", JSON.toJSONString(user));
    return userMapper.updateById(user);
}

基于@CreateCache注解创建Cache实例

@CreateCache
/**
 * 使用 @CreateCache 注解创建Cache实例;
 * 未定义默认值的参数,将使用yml中指定的全局配置;
 * 缓存在 Local,也可以配置成 both 开启两级缓存
 */
@CreateCache(name = CACHE_NAME, expire = 5 * 60, localLimit = 10, cacheType = CacheType.LOCAL)
private Cache<Long, UserVO> userCache;
查询缓存
public UserVO getUserByIdAndCreateCache(Long userId) {
    //根据id从缓存中取
    UserVO userVO = userCache.get(userId);
    log.info("userCreateCache get {} res {}", userId, userCache);
    if (Objects.isNull(userVO)) {
        User user = userMapper.selectById(userId);
        if (Objects.nonNull(user)) {
            userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            //如果不存在就放入缓存中
            boolean res = userCache.putIfAbsent(user.getId(), userVO);
            log.info("userCreateCache putIfAbsent {} res {}", userId, res);
        }
    }
    return userVO;
}
删除缓存
@Transactional(rollbackFor = Exception.class)
public int deleteUserByIdAndCreateCache(Long userId) {
    User user = new User();
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.lambda().eq(User::getId, userId).eq(User::getEnable, 1);
    user.setId(userId);
    user.setEnable(0);
    int result = userMapper.update(user, updateWrapper);
    if (result > 0) {
        //根据key = userId删除缓存
        boolean deleteResult = userCache.remove(userId);
        log.info("同步删除缓存, userId = {}, res = {}", userId, deleteResult);
    }
    return result;
}