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();
        }
    }
}
相关推荐
等什么君!4 分钟前
SpringMVC处理请求映射路径和接收参数
java·开发语言·spring
曹牧12 分钟前
Java:XML被自动转义
xml·java·开发语言
EnigmaCoder16 分钟前
java面向对象编程【基础篇】之基础语法
java·开发语言
啊阿狸不会拉杆20 分钟前
数据结构-图
java·c语言·数据结构·c++·python·算法·图论
码熔burning37 分钟前
【MQ篇】初识RabbitMQ保证消息可靠性
java·分布式·rabbitmq·可靠性
北漂老男孩1 小时前
Spring Boot 自动配置深度解析:从源码结构到设计哲学
java·spring boot·后端
搬砖天才、1 小时前
日常记录-redis主从复制(master-slave)+ Sentinel 哨兵(高可用)
数据库·redis·sentinel
unique_落尘1 小时前
java操作打印机直接打印及详细linux部署(只适用于机器和打印机处于同一个网段中)
java·linux·打印机
小咕聊编程1 小时前
【含文档+PPT+源码】基于SpringBoot+Vue的移动台账管理系统
java·spring boot·后端
佩奇的技术笔记1 小时前
Java学习手册:TCP 协议基础
java·tcp/ip