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();
        }
    }
}
相关推荐
Grey Zeng7 小时前
Java SE 25新增特性
java·jdk·jdk新特性·jdk25
雨白8 小时前
Java 线程通信基础:interrupt、wait 和 notifyAll 详解
android·java
AAA修煤气灶刘哥9 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
架构师沉默12 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
Java中文社群13 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
每天进步一点_JL14 小时前
JVM 类加载:双亲委派机制
java·后端
用户2986985301415 小时前
Java HTML 转 Word 完整指南
java·后端
渣哥15 小时前
原来公平锁和非公平锁差别这么大
java
渣哥15 小时前
99% 的人没搞懂:Semaphore 到底是干啥的?
java
J2K15 小时前
JDK都25了,你还没用过ZGC?那真得补补课了
java·jvm·后端