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();
        }
    }
}
相关推荐
Billow_lamb16 分钟前
redis 中 redisTemplate 的所有操作与函数
数据库·redis·缓存
郑州光合科技余经理31 分钟前
实战:攻克海外版同城生活服务平台开发五大挑战
java·开发语言·javascript·数据库·git·php·生活
蟹至之32 分钟前
【MySQL】JDBC的使用(万字解析)
java·数据库·mysql·jdbc
爱笑的眼睛1133 分钟前
超越翻转与裁剪:面向生产级AI的数据增强深度实践与多模态演进
java·人工智能·python·ai
长孙阮柯35 分钟前
Java进阶篇(五)
java·开发语言
小张快跑。1 小时前
Maven指定版本下载以及相关配置
java·maven
zhishidi1 小时前
Spring @Scheduled注解调度机制详解
java·python·spring
⑩-1 小时前
Blocked与Wati的区别
java·开发语言
AAA简单玩转程序设计1 小时前
救命!Java这3个小技巧,写起来爽到飞起✨
java
IManiy1 小时前
Java表达式引擎技术选型分析(SpEL、QLExpress)
java·开发语言