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

Spring Boot中刷新Map缓存的Flux WebClient配置问题求助

Spring Boot中WebClient Flux缓存的连接失效问题及解决方案探讨

我在Spring Boot环境中,将对应不同主机的WebClient的Flux实例存储在Map中做缓存,前端请求同一数据源时直接返回缓存数据,无需新建WebClient实例,该方案日常运行顺畅。但当目标实例的IP/端口变更后,缓存的WebClient会指向无效连接,导致用户无法获取数据。

我自己设想了几种解决方案:

  • 检测无活跃订阅者时从Map中删除对应实例
  • 定时清理未使用/连接失败的Flux实例
  • 通过反向传播机制替换连接配置

以下是缓存管理器的代码实现:

public abstract class CachedFluxReactiveManager<T, M extends FiltreableCommand> extends CachedReactiveManager<T, M, Flux<T>> {
protected final Map<ReactiveCallsKey, Flux<T>> connections = new ConcurrentHashMap<>();
protected final FluxClientCreator<T> clientCreator;
protected final InstancesQueryCreator queryCreator;
private final boolean useCache;

protected CachedFluxReactiveManager(InstancesCache instancesCache, FluxClientCreator<T> clientCreator,
        InstancesQueryCreator queryCreator, boolean useCache) {
    super(instancesCache);
    this.clientCreator = clientCreator;
    this.queryCreator = queryCreator;
    this.useCache = useCache;
}

@Override
public Flux<T> getData(M command) {

    if (useCache) {
        if (command.isFiltered()) {
            return createAndReturnConnection(command).next().flux();
        }

        return ofNullable(getConnectionIfExists(command))
                .orElseGet(() -> createAndReturnConnection(command));
    } else {
        return createAndReturnConnection(command);
    }
}

@Override
protected Flux<T> getConnectionIfExists(M command) {
    return connections.get(
            getReactiveCallsKey(command.getApplicationName(), command.getTicker(), command.getReferenceEx()));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 05:15:32