Backend Development 11 min read

Using JetCache for Multi‑Level Caching in Spring Boot Applications

This article introduces Alibaba's JetCache framework, explains how to configure and combine local and remote (Redis) caches in a Spring Boot project, and demonstrates three usage patterns—AOP annotations, API mode, and advanced CacheManager API—along with troubleshooting tips and test procedures.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Using JetCache for Multi‑Level Caching in Spring Boot Applications

Hello everyone, I am Chen. In real‑world scenarios we often combine local caches with Redis to meet different business needs, and JetCache helps us achieve elegant multi‑level caching.

1. JetCache Introduction

jetcache is an open‑source Java caching framework from Alibaba that supports multiple cache types: local, distributed, and multi‑level. It is easy to use, high‑performance, and extensible, offering features such as cache warming and key prefixes. When combined with Spring Cache, cache type switching becomes very convenient.

Official site: https://github.com/alibaba/jetcache

2. JetCache Usage

2.1 Add dependencies (Spring Boot project with Redis as remote cache):

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

<!-- For JetCache 2.7.x you also need the Jedis client -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>4.3.1</version>
</dependency>

2.2 Configure application.yml (or application.properties ) for Redis and thread pool settings:

jetcache:
  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: 6379

2.3 Enable caching in the Spring Boot main class:

@EnableCreateCacheAnnotation
@EnableMethodCache(basePackages = "com.example.jetcachedemo")

2.4 Three ways to use the cache:

AOP mode (recommended) : annotate methods with @Cached , @CacheUpdate , @CacheInvalidate .

API mode : use @CreateCache (deprecated after 2.7, not recommended).

Advanced API mode : obtain a CacheManager and create caches programmatically (available from 2.7).

Example of AOP mode:

@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) {
        System.out.println("First fetch, cache miss: " + id);
        User user = new User();
        user.setId(id);
        user.setName("userRemote" + id);
        user.setAge(23);
        user.setSex(1);
        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) { return true; }

    @PostMapping("deleteUser")
    @CacheInvalidate(name="userCache:", key="#id")
    public Boolean deleteUser(Long id) { return true; }
}

Note: the User class must implement Serializable :

@Data
public class User implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    private Integer sex;
}

API mode example (using @CreateCache ) and advanced API mode (using CacheManager ) are also provided in the original article with full code snippets.

3. Testing

3.1 AOP mode test: access localhost:8088/user/getRemote?id=1 and verify the key appears in Redis.

3.2 API mode test: access localhost:8088/user2/get?id=4 (CreateCache) and observe Redis storage; switch to CacheType.LOCAL and confirm the key is only in local cache.

3.3 Advanced API mode test: access localhost:8088/user3/get?id=11 and see the key stored in Redis.

4. Common Errors

• ClassNotFoundException: com.alibaba.fastjson.JSON – add FastJSON dependency.

• NoClassDefFoundError: redis/clients/jedis/UnifiedJedis – add Jedis dependency or downgrade JetCache to ≤2.6.5.

Source of the article: https://juejin.cn/post/7247151913437937701

At the end, the author asks readers to like, follow, share, and consider joining his knowledge community for more advanced content.

JavaRediscachingSpring Bootmulti-level cacheJetCache
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.