JetCache 使用教程
项目介绍
JetCache 是一个基于 Java 的缓存系统封装,提供统一的 API 和注解来简化缓存的使用。JetCache 提供了比 Spring Cache 更加强大的注解,可以原生的支持 TTL(Time To Live)、两级缓存、分布式自动刷新,还提供了 Cache 接口用于手工缓存操作。当前有四个实现:RedisCache、TairCache(此部分未在 GitHub 开源)、CaffeineCache(内存缓存)和一个简易的 LinkedHashMapCache(内存缓存)。
项目快速启动
添加 Maven 依赖
首先,在你的 Maven 项目中添加 JetCache 的依赖:
<dependency>
<groupId>com.alicp</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.5.11</version>
</dependency>
配置 JetCache
在 application.yml 文件中配置 JetCache:
jetcache:
statIntervalMinutes: 15
areaInCacheName: false
local:
default:
type: linkedhashmap
keyConvertor: fastjson2
limit: 100
remote:
default:
type: redis
keyConvertor: fastjson2
broadcastChannel: projectA
valueEncoder: java
valueDecoder: java
poolConfig:
minIdle: 5
maxIdle: 20
maxTotal: 50
host: ${redis.host}
port: ${redis.port}
启动类配置
在 Spring Boot 启动类中开启缓存:
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
import com.alicp.jetcache.anno.config.EnableMethodCache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableMethodCache(basePackages = "com.cxytiandi.jetcache")
@EnableCreateCacheAnnotation
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
应用案例和最佳实践
声明式缓存
使用注解进行声明式缓存:
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Cached(name = "userCache", key = "#userId", cacheType = CacheType.REMOTE)
public User getUserById(String userId) {
// 从数据库或其他服务获取用户信息
return userRepository.findById(userId);
}
}
手动缓存操作
使用 Cache 接口进行手动缓存操作:
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@CreateCache(name = "userCache", cacheType = CacheType.REMOTE)
private Cache<String, User> userCache;
public User getUserById(String userId) {
User user = userCache.get(userId);
if (user == null) {
user = userRepository.findById(userId);
userCache.put(userId, user);
}
return user;
}
}
典型生态项目
JetCache 可以与以下生态项目结合使用,以提供更强大的缓存功能:
- Spring Boot: JetCache 提供了对 Spring Boot 的自动配置支持,可以轻松集成到 Spring Boot 项目中。
- Redis: JetCache 支持 Redis 作为远程缓存,提供高性能的分布式缓存解决方案。
- Caffeine: JetCache 支持 Caffeine 作为本地缓存,提供高效的内存缓存。
- Spring Cloud: 结合 Spring Cloud 使用,可以实现分布式环境下的缓存一致性和自动刷新。
通过以上模块的介绍和示例,您可以
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



