一、依赖版本

<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
<spring-cloud.version>Greenwich.SR5</spring-cloud.version>
<spring-cloud-alibaba.version>2.1.1.RELEASE</spring-cloud-alibaba.version>

二、创建gateway路由配置(json格式)

在nacos中public命名空间下创建配置:

Data ID: gateway-router

Group: DEFAULT_GROUP

配置内容:

[
    {
        "id":"login_route",
        "predicates":[
            {
                "name":"Path",
                "args":{
                    "_genkey_0":"/api/admin/user/login/*",
                    "_genkey_1":"/api/admin/user/permission/*"
                }
            }
        ],
        "filters":[
            {
                "name":"SystemLogin"
            }
        ],
        "uri":"lb://com-petkit-uaa"
    },
    {
        "id":"send_code_route",
        "predicates":[
            {
                "name":"Path",
                "args":{
                    "_genkey_0":"/api/admin/user/login/mobile/validation/*"
                }
            },
            {
                "name":"Domain",
                "args":{
                    "_genkey_0":"**.localhost",
                    "_genkey_1":"**-admin-chain.cn"
                }
            }
        ],
        "filters":[
            {
                "name":"SystemLogin"
            }
        ],
        "uri":"lb://com-petkit-food-admin"
    },
    {
        "id":"admin_route",
        "predicates":[
            {
                "name":"Domain",
                "args":{
                    "_genkey_0":"**.localhost",
                    "_genkey_1":"**-admin-chain.cn"
                }
            }
        ],
        "uri":"lb://com-petkit-food-admin"
    }
]

三、监听路由变化

/**
 * @author menglinjie
 * @date Created in 2020/7/10 11:39
 * @description: 动态路由配置
 */
@RefreshScope
@Slf4j
@Component
public class DynamicRouteConfig implements ApplicationEventPublisherAware {

    /**
     * nacos 配置dataId
     */
    @Value("${config.dynamic.route.dataId:gateway-router}")
    private String dataId = "gateway-router";
    /**
     * nacos 配置group
     */
    @Value("${config.dynamic.route.group:DEFAULT_GROUP}")
    private String group = "DEFAULT_GROUP";

    /**
     * nacos 配置地址
     */
    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher applicationEventPublisher;

    private static final List<String> ROUTE_LIST = new ArrayList<>();

    @PostConstruct
    public void dynamicRouteByNacosListener() {
        try {
            ConfigService configService = NacosFactory.createConfigService(serverAddr);

            // 程序首次启动, 并加载初始化路由配置
            String initConfigInfo = configService.getConfig(dataId, group, 5000);
            this.addAndPublishBatchRoute(initConfigInfo);

            //添加监听路由变化
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    clearRoute();
                    try {
                        List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
                        for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
                            addRoute(routeDefinition);
                        }
                        publish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }


    private void publish() {
        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
    }

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

    /**
     * 批量 添加及发布 路由
     *
     * @param configInfo 配置文件字符串, 必须为json array格式
     */
    private void addAndPublishBatchRoute(String configInfo) {
        try {
            clearRoute();
            List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
            for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
                addRoute(routeDefinition);
            }
            publish();
            log.info("Dynamic config gateway route finished. {}", JSON.toJSONString(gatewayRouteDefinitions));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除路由信息
     */
    private void clearRoute() {
        for (String id : ROUTE_LIST) {
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
    }

    /**
     * 添加路由
     *
     * @param definition
     */
    private void addRoute(RouteDefinition definition) {
        try {
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
            ROUTE_LIST.add(definition.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

注意:ConfigService只能根据dataId、group获取nacos配置,无法指定命名空间获取配置。所以gateway-router路由配置必须在公共命名空间创建,否则无法读取。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐