SpringCloud gateway如何实现动态路由

1 通知SpringBoot配置文件有变化
ApplicationContext..publishEvent(new EnvironmentChangeEvent(changedKeys));
2 通知gateway刷新路由
ApplicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));

以apollo配置中心为例,SpringCloud gateway实现动态路由代码如下:

package com.sa.config;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

/**
 * apollo动态路由
 *
 * @author gongmin
 * @date 2024/1/23 15:06
 */
@Component
@Slf4j
public class GatewayPropertiesRefresher implements ApplicationContextAware, ApplicationEventPublisherAware {
    private ApplicationContext applicationContext;
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    /**
     * 监听apollo配置,实现网关路由动态更新
     *
     * @param changeEvent 更新事件
     */
    @ApolloConfigChangeListener(value = "application.yml", interestedKeyPrefixes = "spring.cloud.gateway.")
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshGatewayProperties(changeEvent);
    }

    /**
     * 刷新路由
     *
     * @param changeEvent 更新事件
     */
    private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
        log.debug("<refreshGatewayProperties> start");
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshGatewayRouteDefinition();
        log.debug("<refreshGatewayProperties> end");
    }

    /**
     * 刷新路由
     */
    private void refreshGatewayRouteDefinition() {
        log.debug("<refreshGatewayRouteDefinition> start");
        this.publisher.publishEvent(new RefreshRoutesEvent(this));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容