spring cloud gateway使用redis存储时,断网重连会导致路由丢失解决方案

注册event bus

java 复制代码
import io.lettuce.core.event.EventBus;
import io.lettuce.core.resource.ClientResources;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.util.Optional;

@Configuration
public class RedisConnectionEventBusAutoConfig {

    @Bean
    public EventBus lettuceEventBus(LettuceConnectionFactory lettuceConnectionFactory) {
        Optional<ClientResources> clientResources = lettuceConnectionFactory.getClientConfiguration()
                .getClientResources();
        boolean present = clientResources.isPresent();
        return present ? clientResources.get().eventBus() : null;
    }
}

监听事件

java 复制代码
import com.jinlei.gateway.sirius.application.RouteDefinitionService;
import io.lettuce.core.event.EventBus;
import io.lettuce.core.event.connection.ConnectionActivatedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import reactor.core.Disposable;


@Component
@RequiredArgsConstructor
@Slf4j
public class RedisConnectionEventListener {

    private Disposable subscription;
    private final RouteDefinitionService routeDefinitionService;

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        EventBus eventBus = event.getApplicationContext().getBean(EventBus.class);
        // 订阅事件
        subscription = eventBus.get().subscribe(redisEvent -> {
            if (redisEvent instanceof ConnectionActivatedEvent) {
                ConnectionActivatedEvent connectionActivatedEvent = (ConnectionActivatedEvent) redisEvent;
                log.info("Redis reconnect ..try refresh route: {}", connectionActivatedEvent);
                routeDefinitionService.refreshRouteDefinition();
            }
        });
    }

    // 清理资源
    @EventListener
    public void onApplicationStop(ContextClosedEvent event) {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }
}
相关推荐
小碗羊肉9 小时前
【Redis | 第三篇】缓存(Cache)
数据库·redis·缓存
阿维的博客日记9 小时前
简单介绍一下CompletableFuture,从最简单的用法介绍,
java
zandy10119 小时前
2026 BI平台安全治理体系构建:从权限模型到零信任架构
java·开发语言
SuniaWang9 小时前
《Agentx专栏》02-技术选型:预算有限时如何做出正确的技术决策
java·spring·架构·langchain·milvus·agenx·opl
羡寒.9 小时前
接口突然变慢,你怎么排查?
java·后端·spring
zuowei28899 小时前
编程语言对比:C/C++/Java/C#/PHP
java·c语言·c++
百数平台9 小时前
功能更新——百数详情页“数据简报”与“关联标签页”配置指南
java·服务器·前端
接着奏乐接着舞9 小时前
java lambda表达式
java·开发语言·python
金銀銅鐵9 小时前
[Java] 自己写程序,来解析字段的 descriptor
java·后端
ch.ju9 小时前
Java程序设计(第3版)第四章——成员方法
java·开发语言