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();
        }
    }
}
相关推荐
四谎真好看8 分钟前
Java 黑马程序员学习笔记(进阶篇20)
java·笔记·学习·学习笔记
BUTCHER59 分钟前
【原理扫描】SSL/TLS 服务器瞬时 Difie-Hellman 公共密钥过弱
java·服务器·网络·ssl
聪明的笨猪猪9 分钟前
hot 100 (1)—— 两数之和(哈希)
java·经验分享·算法·哈希算法
梵得儿SHI9 分钟前
Java 注解与反射实战:自定义注解从入门到精通
java·开发语言·注解·自定义注解·元注解·控制注解的作用·声明式编程思想
DemonAvenger19 分钟前
深入 Redis Hash:从原理到实战,10 年经验的后端工程师带你玩转哈希结构
数据库·redis·性能优化
速易达网络43 分钟前
Java Web登录系统实现(不使用开发工具)
java·开发语言·前端
悟能不能悟1 小时前
java重构旧代码有哪些注意的点
java·开发语言·重构
怪兽20142 小时前
Redis过期键的删除策略有哪些?
java·数据库·redis·缓存·面试
workflower5 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
YuanlongWang5 小时前
C# 基础——装箱和拆箱
java·开发语言·c#