Comprehensive Guide to Using JetCache for Multi‑Level Caching in Spring Boot
This article introduces Alibaba's JetCache Java caching framework, explains how to integrate it with Spring Boot and Redis, provides detailed configuration and code examples for local, remote, and multi‑level caches, and covers testing procedures and common error resolutions.
JetCache is an open‑source Java caching framework from Alibaba that supports multiple cache types—including local, distributed, and multi‑level caches—allowing developers to combine them to meet diverse business requirements.
1. JetCache Introduction
JetCache offers simple onboarding, high performance, and strong extensibility, with features such as cache pre‑warming and key prefixes. It can be used together with Spring Cache for seamless cache type switching.
Official repository: https://github.com/alibaba/jetcache
Documentation: https://github.com/alibaba/jetcache/tree/master/docs/CN
2. Using JetCache
2.1 Add Dependency
<dependency>
<groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis</artifactId>
<version>2.7.0</version>
</dependency>
<!-- jetcache 2.7.x also requires jedis dependency -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>2.2 Configure Application
jetcache:
# Statistics interval, 0 means disabled
statIntervalMinutes: 15
areaInCacheName: false
local:
default:
type: linkedhashmap
keyConvertor: fastjson
remote:
default:
type: redis
keyConvertor: fastjson
broadcastChannel: projectA
valueEncoder: java
valueDecoder: java
poolConfig:
minIdle: 5
maxIdle: 20
maxTotal: 50
host: 127.0.0.1
port: 63792.3 Enable Annotations
Add the following annotations to the Spring Boot main class to activate JetCache:
@EnableCreateCacheAnnotation
@EnableMethodCache(basePackages = "com.example.jetcachedemo")2.4 Cache Usage (AOP Mode)
Use the annotations @Cached , @CacheUpdate and @CacheInvalidate on controller methods:
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("getRemote")
@Cached(name="userCache:", key="#id", expire=3600, timeUnit=TimeUnit.SECONDS, cacheType=CacheType.REMOTE)
public User getRemote(Long id) {
User user = new User();
user.setId(id);
user.setName("用户remote" + id);
user.setAge(23);
user.setSex(1);
System.out.println("第一次获取数据,未走缓存:" + id);
return user;
}
@GetMapping("getLocal")
@Cached(name="userCache:", key="#id", expire=3600, timeUnit=TimeUnit.SECONDS, cacheType=CacheType.LOCAL)
public User getLocal(Long id) { /* similar implementation */ }
@GetMapping("getBoth")
@Cached(name="userCache:", key="#id", expire=3600, timeUnit=TimeUnit.SECONDS, cacheType=CacheType.BOTH)
public User getBoth(Long id) { /* similar implementation */ }
@PostMapping("updateUser")
@CacheUpdate(name="userCache:", key="#user.id", value="#user")
public Boolean updateUser(@RequestBody User user) {
// TODO: update DB
return true;
}
@PostMapping("deleteUser")
@CacheInvalidate(name="userCache:", key="#id")
public Boolean deleteUser(Long id) {
// TODO: delete from DB
return true;
}
}Ensure the User class implements Serializable :
@Data
public class User implements Serializable {
private Long id;
private String name;
private Integer age;
private Integer sex;
}2.5 API Mode (CreateCache)
For JetCache 2.7.x, the @CreateCache annotation is deprecated. Example usage:
@RestController
@RequestMapping("user2")
public class User2Controller {
@CreateCache(name="userCache:", expire=3600, timeUnit=TimeUnit.SECONDS, cacheType=CacheType.BOTH)
private Cache
userCache;
// get, updateUser, deleteUser methods similar to AOP mode
}2.6 Advanced API (CacheManager)
Add FastJSON dependency and create a configuration class:
@Configuration
public class JetcacheConfig {
@Autowired
private CacheManager cacheManager;
private Cache
userCache;
@PostConstruct
public void init() {
QuickConfig qc = QuickConfig.newBuilder("userCache:")
.expire(Duration.ofSeconds(3600))
.cacheType(CacheType.BOTH)
.syncLocal(false)
.build();
userCache = cacheManager.getOrCreateCache(qc);
}
@Bean
public Cache
getUserCache() {
return userCache;
}
}Use the cache in a controller:
@RestController
@RequestMapping("user3")
public class User3Controller {
@Autowired
private Cache
userCache;
// get, updateUser, deleteUser methods similar to previous examples
}3. Testing
Access localhost:8088/user/getRemote?id=1 to test remote cache; the key appears in Redis. Access localhost:8088/user/getLocal?id=1 to verify local cache fallback when remote data is missing. Similar tests are shown for API mode and advanced API mode, confirming that cache entries are correctly stored in Redis or only locally depending on configuration.
4. Common Errors
ClassNotFoundException: com.alibaba.fastjson.JSON – add FastJSON dependency.
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.25</version>
</dependency>NoClassDefFoundError: redis/clients/jedis/UnifiedJedis – add Jedis dependency or downgrade JetCache to 2.6.5 or lower.
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>After resolving these issues, the multi‑level caching setup works as expected.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.