Spring Boot中使用JetCache

1. 什么是JetCache

JetCache是一个基于Java的缓存系统封装,提供统一的API和强大的注解来简化缓存的使用。原生支持TTL、两级缓存、分布式自动刷新,还提供了Cache接口用于手工缓存操作。

全部特性:

  • 通过统一的API访问Cache系统
  • 通过注解实现声明式的方法缓存,支持TTL和两级缓存
  • 通过注解创建并配置Cache实例
  • 针对所有Cache实例和方法缓存的自动统计
  • Key的生成策略和Value的序列化策略是可以配置的
  • 分布式缓存自动刷新,分布式锁 (2.2+)
  • 异步Cache API (2.2+,使用Redis的lettuce客户端时)

2. JetCache的基本使用方式

这里主要讲述Spring boot中的JetCache使用方式

2.1 配置文件

pom文件

<dependency>
     <groupId>com.alicp.jetcache</groupId>
     <artifactId>jetcache-starter-redis</artifactId>
     <version>2.5.11</version>
</dependency>

在(resources)资源文件目录下新建一个springboot风格的application.yml文件

jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: linkedhashmap
      keyConvertor: fastjson
      limit: 100
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 127.0.0.1
      port: 6379
      password: 123456

2.2 代码实例

在代码中有2种方式实现缓存

2.2.1 创建缓存实例

通过@CreateCache注解创建一个缓存实例,然后像操作map一样操作这个缓存实例,默认缓存时间是100秒

public interface UserService {

    User getUserById(Long userId);

    void updateUser(User user);

    void deleteUser(Long userId);
}

@Service
public class UserServiceImpl implements UserService {

    @CreateCache(name = "user_cache_", expire = 3600, cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<Long, User> userCache;

    @Override
    public User getUserById(Long userId) {
        User user = userCache.get(userId);
        if (user != null) {
            return user;
        }
        user = new User(userId, "张杰", 18);
        userCache.put(userId, user);
        return user;
    }

    @Override
    public void updateUser(User user) {
        userCache.put(user.getUserId(), user);
        System.out.println("updateUser:" + user);
    }

    @Override
    public void deleteUser(Long userId) {
        userCache.remove(userId);
        System.out.println("deleteUser :" + userId);
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 220401161187822517L;

    private Long userId;
    private String name;
    private Integer age;
}
2.2.2 创建方法缓存

使用@Cached方法为一个方法添加上缓存。JetCache通过Spring AOP生成代理,来支持缓存功能。注解可以加在接口方法上也可以加在类方法上,但需要保证是个Springbean。

public interface StudentService {

    @Cached(name = "student_cache_", key = "#id", expire = 3600)
    Student getStudentById(Long id);

    @CacheUpdate(name = "student_cache_", key = "#id", value = "#student")
    void updateStudent(Student student);

    @CacheInvalidate(name = "student_cache_", key = "#id")
    void deleteStudent(Long id);
}

@Service
public class StudentServiceImpl implements StudentService {

    @Override
    public Student getStudentById(Long userId) {
        return new Student(userId, "张杰", 18);
    }

    @Override
    public void updateStudent(Student user) {
        System.out.println("updateUser:" + user);
    }

    @Override
    public void deleteStudent(Long userId) {
        System.out.println("deleteUser :" + userId);
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
    private static final long serialVersionUID = -6832900779447088497L;

    private Long id;
    private String name;
    private Integer age;
}

3. JetCache使用注意的问题

  • 运行报错:java.lang.NoSuchMethodError: redis.clients.jedis.JedisPool.(Lorg/apache/commons/pool2/impl/GenericObjectPoolConfig;Ljava/lang/String;IILjava/lang/String;ILjava/lang/String;Z)V
    遇到这种错误原因是依赖包jedis版本太低,你需要引入新版本的jedis:
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.9.0</version>
</dependency>
  • @CreateCache注解创建缓存实例无效,执行时缓存实例一直是null,原因是jetcache版本问题,我原本使用的是2.5.3版本,后来换了2.5.11版本就好了
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值