SpringBoot Cache Annotations: Integrating Redis-based @CacheResult for SpringBoot Projects

Preface

Adding cache to an existing SpringBoot service typically involves hand-writing Redis utility classes or wrapping every query method with get/set logic. Annotation-based caching reduces duplicate code, but aligning Spring Cache with business-defined key rules, null value semantics, and SpEL customized keys still requires manual implementation. Below is an introduction to the SkillHub community skill springboot缓存注解 (Coordinates: @user_faca7523/springboot-cache, Version: 1.0.0): It uses a script to inject @CacheResult, AOP aspects, Redis configuration, and dependencies into your project all at once. It is suitable for extending the foundational structure generated by springboot-init.

What is this

springboot缓存注解 is a SpringBoot-oriented Agent Skill published by user_faca7523. It is categorized under dev-programming and originates from the community. The skill’s goal is clear: to add Redis-based caching annotation capabilities to SpringBoot projects, using @CacheResult to cache method return values.

This skill declares a dependency on the base project structure generated by the springboot-init skill. If a standalone empty repository does not match the directory conventions, the corresponding skeleton must be prepared before executing the script.

Core Features

@CacheResult Annotation Parameters

Parameter Type Default Value Description
keyPrefix String project:cache Prefix for the cache key
key String "" Static cache key
spelKey String "" SpEL expression cache key
cacheTime int 1 Cache duration
cacheTimeUnit TimeUnit TimeUnit.HOURS Cache duration unit

Key Generation Strategy

  1. Priority 1: Static Key: keyPrefix:key
  2. Priority 2: SpEL: keyPrefix:resolved_SpEL_expression
  3. Default: keyPrefix:FullyQualifiedClassName:MethodName:AES(args) (The documentation describes the default strategy as applying AES to arguments; however, the technical features section also mentions using Hutool MD5 to generate deterministic keys. In practice, the generated code is the definitive source.)

Project Content Generated by the Script

Dependencies (pom.xml)

  • cn.hutool:hutool-all
  • spring-boot-starter-data-redis
  • spring-boot-starter-aop

application.yml will be updated with Redis connection settings, for example:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      password:
      database: 0
      timeout: 3000ms

New or Updated Java Files

File Path Description
annotation/CacheResult.java Cache annotation
common/CacheNullValue.java Null value marker class
util/CacheKeyGenerator.java Key generation utility class
aspect/CacheResultAspect.java Cache AOP aspect
config/RedisConfig.java Redis configuration class

Technical Features (Official Description)

  1. Uses Hutool MD5 utility to generate deterministic keys.
  2. SpEL supports #paramName, #param.property, etc.
  3. Distinguishes between “not cached” and “cached null” via CacheNullValue.
  4. Cache operation failures do not affect business execution.
  5. Uses GenericJackson2JsonRedisSerializer to serialize complex objects.

Installation and Activation

After installing the skill, the typical path is .trae/skills/springboot-cache/. Execute the script in the root directory of a project that already has the springboot-init structure to inject caching capabilities for a specified artifactId and package name:

python .trae/skills/springboot-cache/scripts/cache_annotation.py <artifactId> <packageName> [projectName] [springBootVersion] [author]

Examples:

# Basic usage
python .trae/skills/springboot-cache/scripts/cache_annotation.py demo com.example

# Specifying project information
python .trae/skills/springboot-cache/scripts/cache_annotation.py demo com.example Demo 3.5 wql

Parameter meanings: artifactId and packageName are required; projectName, springBootVersion, and author are optional. Please ensure the local Redis address matches the configuration in application.yml before execution. If the documentation does not list specific steps for Cursor / Codex CLI / Claude Code, refer to the scripts within the Skill directory and SKILL.md.

The SkillHub page displays the tag requires_api_key=false for this skill, meaning no additional API Key is needed.

Typical Usage

Declare @CacheResult on a Service or query method, choosing one of the three key strategies or combining time and units:

// Using a static key
@CacheResult(keyPrefix = "user:", key = "info")
public User getUser(Long userId) {
    // ...
}

// Using a SpEL key
@CacheResult(keyPrefix = "user:", spelKey = "#userId")
public User getUser(Long userId) {
    // ...
}

// Using the default key and setting a 30-minute expiration
@CacheResult(cacheTime = 30, cacheTimeUnit = TimeUnit.MINUTES)
public User getUser(Long userId) {
    // ...
}

With the steps above, the first call executes the method logic and writes to Redis; subsequent calls with the same key return the cache directly via the aspect within the validity period. To penetrate or update the cache, you should manage expiration in the business layer or extend the invalidation logic yourself (the skill documentation does not include built-in @CacheEvict style annotations; capabilities are limited to the generated code).

Applicable Scenarios and Notes

Suitable for

  • SpringBoot projects built or planned with springboot-init that need to quickly add Redis + annotation caching.
  • Scenarios requiring unified key prefixes, SpEL support, and handling of null cache semantics.

Notes

  1. Prerequisites: The project structure defined by springboot-init must exist first; otherwise, the script’s target paths may not align.
  2. Runtime Environment: A working Redis instance is required; the default is localhost:6379. Production environments should change the host, password, and database.
  3. Serialization: Complex objects rely on Jackson JSON serialization. Type changes may cause old cache deserialization to fail. It is advisable to clear keys or shorten TTL after model changes.
  4. Failure Strategy: Cache exceptions do not block business logic but may cause short-term database load (breakdown). Monitoring should be used to observe Redis availability.

Conclusion

springboot缓存注解 encapsulates Redis dependencies, configuration, the @CacheResult aspect, and key strategies into a scriptable, one-step integration. It is suitable for adding a caching layer to a standard SpringBoot skeleton. For more details and installation, visit SkillHub:

  • API Documentation: https://api.skillhub.cn/user_faca7523/springboot-cache
  • Skill Page: https://www.skillhub.cn/skills/user_faca7523/springboot-cache
羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye