SpringBoot @Cacheable自定义KeyGenerator

1. 概述

SpringBoot 使用 @Cacheable 可以方便的管理缓存数据,在不指定 key 属性的情况下,默认使用 SimpleKeyGenerator 生成 key。除此之外,我们也可以自定义实现 KeyGenerator 接口,生成自己的 key 名称策略。

2. MySimpleKey 类

MySimpleKey类的作用是存放参数数据,必须实现equals、hashCode。如果需要自定义key格式,同样需要实现toString接口,下面的例子是把参数用逗号分隔。

public class MySimpleKey implements Serializable {
    public static final MySimpleKey EMPTY = new MySimpleKey(new Object[0]);
    private final Object[] params;
    private transient int hashCode;

    public MySimpleKey(Object... elements) {
        Assert.notNull(elements, "Elements must not be null");
        this.params = (Object[])elements.clone();
        this.hashCode = Arrays.deepHashCode(this.params);
    }

    public boolean equals(@Nullable Object other) {
        return this == other || other instanceof MySimpleKey && Arrays.deepEquals(this.params, ((MySimpleKey)other).params);
    }

    public final int hashCode() {
        return this.hashCode;
    }

    public String toString() {
        return StringUtils.arrayToCommaDelimitedString(this.params);
    }
}

3. MyKeyGenerator 类

MyKeyGenerator 实现 KeyGenerator 的接口,里面只有一个 generate 方法

public class MyKeyGenerator implements KeyGenerator {
    @Override
    public Object generate(Object o, Method method, Object... objects) {
        if (objects.length == 0) {
            return MySimpleKey.EMPTY;
        } else {
            if (objects.length == 1) {
                Object param = objects[0];
                if (param != null && !param.getClass().isArray()) {
                    return param;
                }
            }

            return new MySimpleKey(objects);
        }
    }
}

定义MyKeyGenerator Bean:

@Component
public class MyRedisConf {

    @Bean
    public MyKeyGenerator myKeyGenerator(){
        return new MyKeyGenerator();
    }
}

4. 配置keyGenerator

在 @Cacheable 配置 keyGenerator 属性,值就是前面配置的Bean名称

    @Override
    @Cacheable(value = {"REDIS:GETSTRING3"}, keyGenerator = "myKeyGenerator")
    public String getString3(String tag, String name) {
        return tag + " " + name;
    }

测试结果如下,tag、name 参数确实以逗号分隔

127.0.0.1:6379[5]> KEYS *
1) "REDIS:GETSTRING3::hello,zhangsan"

### Spring Boot 中 `@Cacheable` 注解不触发的原因及解决方案 #### 配置缺失 为了使 `@Cacheable` 正常工作,项目中必须启用缓存支持。这通常通过在主类或其他配置类上添加 `@EnableCaching` 来完成[^2]。 ```java import org.springframework.cache.annotation.EnableCaching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 缓存管理器未正确配置 如果应用程序没有合适的缓存提供者,则即使存在 `@Cacheable` 注解也不会起作用。确保已经配置了一个具体的缓存实现(如 Redis 或 Ehcache),并且该实现已被注册到应用上下文中作为 `CacheManager` 实现的一部分[^1]。 对于Redis来说,在application.properties文件里设置如下属性: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.cache.type=redis ``` 同时还需要引入相应的依赖项以便能够连接至Redis服务器并利用其存储能力。 #### 方法签名变化影响缓存键生成 当被标记的方法参数列表发生变化时,默认情况下会改变用于查找缓存条目的key值,从而导致每次调用都被视为新请求而绕过了现有缓存数据。可以通过自定义 keyGenerator 解决此问题或者显式指定 cacheKey 属性来保持一致性[^3]。 ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value="users", key="#userId") public User getUserById(Long userId){ return userRepository.findById(userId).orElse(null); } } ``` 在此例子中,“value”指定了要使用的缓存名称;“key”则表示用来区分不同记录的唯一标识符表达式。 #### AOP代理模式的影响 默认情况下,Spring 使用 JDK 动态代理机制创建目标对象实例。这意味着只有外部对该服务方法的调用才会经过AOP拦截器处理进而激活缓存逻辑。因此,内部同一组件内的自我调用不会触发展开行为。可以考虑调整为基于 CGLIB 的子类化方式以覆盖这种情况下的局限性。 ```yaml spring.aop.proxy-target-class=true ``` 上述 YAML 设置告知框架优先采用 CGLIB 技术而非标准接口导向型代理方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

°Fuhb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值