Backend Development 9 min read

Master JetCache in Spring Boot 3: Annotation & Programmatic Caching Guide

This article walks through using JetCache with Spring Boot 3.2.5, covering its features, Maven dependency setup, YAML configuration, annotation-based caching, programmatic cache creation, statistics monitoring, and deprecated APIs, all illustrated with code snippets and screenshots.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master JetCache in Spring Boot 3: Annotation & Programmatic Caching Guide

Environment: Spring Boot 3.2.5

1. Introduction

JetCache is a Java caching framework that provides a unified API and annotations to simplify cache usage. Compared with Spring Cache, JetCache offers stronger annotations supporting TTL, two‑level caching, distributed auto‑refresh, and a manual Cache interface. It currently has four implementations: RedisCache , TairCache (not open‑source), CaffeineCache (in‑memory), and LinkedHashMapCache (in‑memory).

Key features of JetCache include:

Unified API to access cache systems.

Declarative method caching via annotations with TTL and two‑level support.

Annotation‑based creation and configuration of Cache instances.

Automatic statistics for all Cache instances and method caches.

Configurable key generation and value serialization strategies.

Distributed cache auto‑refresh and distributed lock (2.2+).

Asynchronous Cache API (2.2+, when using Redis Lettuce client).

2. Practical Example

2.1 Dependency Management

<code>&lt;dependency&gt;
  &lt;groupId&gt;com.alicp.jetcache&lt;/groupId&gt;
  &lt;artifactId&gt;jetcache-starter-redis&lt;/artifactId&gt;
  &lt;version&gt;2.7.6&lt;/version&gt;
&lt;/dependency&gt;</code>

The latest version is 2.7.6 and supports Spring Boot 3.x and 2.x.

2.2 YAML Configuration

<code>jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: caffeine
      keyConvertor: JACKSON
  remote:
    default:
      type: redis
      keyConvertor: JACKSON
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 127.0.0.1
      port: 6379</code>

Enable caching in the application class:

<code>@SpringBootApplication
@EnableMethodCache(basePackages = "com.pack")
public class AppApplication { }</code>

2.3 Annotation‑Based Usage

JetCache annotations work similarly to Spring Cache but provide native TTL and two‑level support. After Spring Boot 2.4, annotations for cache update and invalidation are also available.

Key annotations:

@Cached : Cache method result.

@CacheUpdate : Update cache entry.

@CacheInvalidate : Remove cache entry.

<code>@Service
public class JetCacheUserService {
    private static final String USER_CACHE_PREFIX = "user:";

    @Cached(name = USER_CACHE_PREFIX, key = "#user.id", expire = 600, timeUnit = TimeUnit.SECONDS)
    public User save(User user) {
        System.err.println("保存用户信息");
        return user;
    }

    @Cached(name = USER_CACHE_PREFIX, key = "#userId")
    public User get(long userId) {
        System.err.println("查询用户信息");
        return new User();
    }

    @CacheUpdate(name = USER_CACHE_PREFIX, key = "#user.id", value = "#user")
    public User updateUser(User user) {
        System.out.println("更新用户信息");
        return user;
    }

    @CacheInvalidate(name = USER_CACHE_PREFIX, key = "#userId")
    public void deleteUser(long userId) {
        System.err.printf("删除用户【%s】%n", userId);
    }
}</code>

Annotation attribute details are illustrated in the following images:

2.4 Cache Statistics

When jetcache.statIntervalMinutes is greater than 0, JetCache automatically logs cache statistics at the configured interval. Example log output is shown below:

2.5 Programmatic Usage

Using CacheManager you can create cache instances manually:

<code>private final CacheManager cacheManager;

public JetCacheProgramUserService(CacheManager cacheManager) {
    this.cacheManager = cacheManager;
}
private Cache<Long, User> userCache;

@PostConstruct
public void init() {
    QuickConfig qc = QuickConfig.newBuilder("user:")
        .expire(Duration.ofSeconds(100))
        .cacheType(CacheType.BOTH)
        .syncLocal(true)
        .build();
    userCache = cacheManager.getOrCreateCache(qc);
}

public User save(User user) {
    System.err.println("Program 保存用户信息");
    userCache.computeIfAbsent(user.getId(), key -> user);
    return user;
}

public User get(long userId) {
    User user = userCache.get(userId);
    if (user == null) {
        System.err.println("查询用户信息");
        // TODO fetch from DB
    }
    return user;
}</code>

The result is equivalent to the annotation‑based approach.

2.6 Deprecated @CreateCache

<code>@CreateCache(expire = 100)
private Cache<Long, User> userCache;</code>

This method is deprecated and not recommended.

Conclusion

The article demonstrates how to integrate JetCache into a Spring Boot project using both annotation‑driven and programmatic techniques, covering dependency setup, configuration, cache operations, statistics, and migration notes.

JavaRediscachingSpring BootannotationJetCache
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

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.