You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java库缓存键无法在Spring Boot应用OrderApp中可见的解决方案咨询

解决方案:让依赖库的缓存键在Spring Boot应用中可见

要解决这个问题,核心是将两个Java库的缓存实现接入Spring Cache体系,替换掉自定义的CacheManager,让Spring统一管理缓存实例,这样OrderApp就能通过Spring的org.springframework.cache.CacheManager查看缓存键。以下是具体步骤:

1. 改造Java库的构建依赖

将原纯Java库转为Spring兼容的库,在构建文件(以Gradle为例)中引入Spring缓存相关依赖:

plugins {
    id 'java'
    id 'io.spring.dependency-management' version '1.1.4'
}

dependencyManagement {
    imports {
        mavenBom 'org.springframework.boot:spring-boot-dependencies:3.2.0' // 匹配目标Spring Boot版本
    }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-cache'
    implementation 'com.github.ben-manes.caffeine:caffeine'
    implementation 'org.springframework.boot:spring-boot-autoconfigure'
}

2. 替换自定义CacheManager为Spring缓存实现

删除原自定义的CacheManager类,改用Spring提供的CaffeineCacheManager,通过配置类定义缓存实例:

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class LibraryCacheConfig {

    // 汇率缓存配置
    @Bean("exchangeRateCacheManager")
    public CacheManager exchangeRateCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("exchange-rate-cache");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(100) // 对应原自定义CacheManager的maxSize
                .expireAfterWrite(3600, TimeUnit.SECONDS)); // 对应原expireAfterWriteSeconds
        return cacheManager;
    }

    // 加密货币缓存配置
    @Bean("cryptoCacheManager")
    public CacheManager cryptoCacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("crypto-symbol-cache");
        cacheManager.setCaffeine(Caffeine.newBuilder()
                .maximumSize(50)
                .expireAfterWrite(1800, TimeUnit.SECONDS));
        return cacheManager;
    }
}

3. 修改库中业务类的缓存使用方式

将原依赖自定义CacheManager的业务代码,改为注入Spring的CacheManager或使用Spring缓存注解:

方式1:注入CacheManager手动操作缓存

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Qualifier;

@Component
public class ExchangeRateService {

    private final Cache exchangeRateCache;

    // 注入指定的缓存管理器
    public ExchangeRateService(@Qualifier("exchangeRateCacheManager") CacheManager cacheManager) {
        this.exchangeRateCache = cacheManager.getCache("exchange-rate-cache");
    }

    public void cacheCountrySymbol(String countryCode, String symbol) {
        exchangeRateCache.put(countryCode, symbol);
    }

    public String getCountrySymbol(String countryCode) {
        Cache.ValueWrapper wrapper = exchangeRateCache.get(countryCode);
        return wrapper != null ? (String) wrapper.get() : null;
    }
}

方式2:使用Spring缓存注解(更简洁)

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class CryptoSymbolService {

    @Cacheable(value = "crypto-symbol-cache", key = "#cryptoCode")
    public String getCryptoSymbol(String cryptoCode) {
        // 原有的符号获取逻辑(比如调用外部API)
        return fetchSymbolFromApi(cryptoCode);
    }

    private String fetchSymbolFromApi(String cryptoCode) {
        // 实际业务逻辑
        return "BTC";
    }
}

4. 配置库的自动加载

在Java库的src/main/resources/META-INF目录下创建spring.factories文件,让OrderApp引入库时自动加载缓存配置:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.yourpackage.LibraryCacheConfig

5. 在OrderApp中查看缓存键

OrderApp只需启用Spring缓存,即可注入对应的CacheManager查看缓存键:

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Qualifier;

@Configuration
@EnableCaching
public class OrderAppCacheConfig {}

@RestController
public class CacheInspectController {

    private final CacheManager exchangeRateCacheManager;
    private final CacheManager cryptoCacheManager;

    public CacheInspectController(@Qualifier("exchangeRateCacheManager") CacheManager exchangeRateCacheManager,
                                  @Qualifier("cryptoCacheManager") CacheManager cryptoCacheManager) {
        this.exchangeRateCacheManager = exchangeRateCacheManager;
        this.cryptoCacheManager = cryptoCacheManager;
    }

    @GetMapping("/exchange-rate-cache-keys")
    public Iterable<?> getExchangeRateCacheKeys() {
        Cache cache = exchangeRateCacheManager.getCache("exchange-rate-cache");
        // 从Caffeine原生缓存中获取键集合
        return ((com.github.benmanes.caffeine.cache.Cache<?, ?>) cache.getNativeCache()).asMap().keySet();
    }

    @GetMapping("/crypto-cache-keys")
    public Iterable<?> getCryptoCacheKeys() {
        Cache cache = cryptoCacheManager.getCache("crypto-symbol-cache");
        return ((com.github.benmanes.caffeine.cache.Cache<?, ?>) cache.getNativeCache()).asMap().keySet();
    }
}

内容的提问来源于stack exchange,提问作者user352290

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 06:41:29