统一缓存库jetcache和SpringBoot整合
简介
jetcache是阿里开源缓存库的封装,它为不同的缓存解决方案提供统一的使用,它提供了比 Spring Cache 中更强大的注解。JetCache 中的注解支持原生 TTL,二级缓存,分布式环境下自动刷新,也可以Cache通过代码操作实例。目前支持本地缓存实现方式:Caffeine、LinkedHashMap。远程缓存实现:redis、tair。
各缓存库缺陷和特性
Spring Cache:远程缓存和本地缓存无法同时使用,不支持过期和缓存刷新。
Guava Cache/Caffeine:本地缓存,无法做分布式缓存。
Redis:分布式缓存,性能没本地缓存好
Ehcache:本地缓存,可通过RMI做分布式缓存,效果不好。
jetcache解决这些问题主要体现在:
- 在Spring Cache 基础上实现了 缓存过期设置、缓存刷新。
- 本地缓存和远程缓存共存方案。
- 注解无法实现的复杂的场景可通过api方式
与SpringBoot整合
pom.xml依赖
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.6.2</version>
</dependency>
启用jetcache
@SpringBootApplication
@EnableCreateCacheAnnotation
// 开启方法注解
@EnableMethodCache(basePackages="com.terry")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
缓存注解的使用
import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheRefresh;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.Cached;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService {
@Data
@AllArgsConstructor
public static class User {
private String name;
private Integer age;
}
// 模拟数据库
List<User> userList = new ArrayList<>();
@CacheUpdate(name = "user", key = "#name", value = "#user")
public void add (User user) {
userList.add(user);
}
// 删除缓存
@CacheInvalidate(name = "user", key = "#name")
public void delete (String name) {
// 删除逻辑
}
// 更新缓存
@CacheUpdate(name = "user", key = "#name", value = "#user")
public void update (User user) {
// 修改逻辑
}
// 查询缓存,缓存过期时间 1小时
@Cached(name="user", expire = 3600)
// 定时5秒刷新缓存
@CacheRefresh(refresh = 5)
public List<User> query(){
System.out.println("查询数据库");
return userList;
}
}
缓存Api的使用
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Service;
@Service
public class UserApiService {
@Data
@AllArgsConstructor
public static class User {
private String name;
private Integer age;
}
// 创建缓存
@CreateCache(name="user",expire = 1000)
private Cache<String ,User> jetCache;
public void add (User user) {
jetCache.put(user.getName(), user);
}
public User get(String name){
return jetCache.get(name);
}
}
