Spring Cloud Gateway實戰之三:動態路由


歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內容:所有原創文章分類匯總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;

本篇概覽

  • 本文是《Spring Cloud Gateway實戰》系列的第三篇,前文介紹了多種路由配置方式,它們存在一個共同問題:路由配置變更后必須重啟Gateway應用才能生效,聰明的您一下就看出了問題關鍵:這樣不適合生產環境!
  • 如何讓變動后的路由立即生效,而無需重啟應用呢?這就是今天的主題:動態路由

設計思路

  • 這里提前將設計思路捋清楚,總的來說就是將配置放在nacos上,寫個監聽器監聽nacos上配置的變化,將變化后的配置更新到Gateway應用的進程內:
  • 上述思路體現在代碼中就是下面三個類:
  1. 將操作路由的代碼封裝到名為RouteOperator的類中,用此類來刪除和增加進程內的路由
  2. 做一個配置類RouteOperatorConfig,可以將RouteOperator作為bean注冊在spring環境中
  3. 監聽nacos上的路由配置文件,一旦有變化就取得最新配置,然后調用RouteOperator的方法更新進程內的路由,這些監聽nacos配置和調用RouteOperator的代碼都放RouteConfigListener類中
  • 在本次實戰中,一共涉及三個配置文件,其中bootstrap.yml + gateway-dynamic-by-nacos是大家熟悉的經典配置,bootstrap.yml 在本地,里面是nacos的配置,gateway-dynamic-by-nacos在naocs上,里面是整個應用所需的配置(例如服務端口號、數據庫等),還有一個配置文件在nacos上,名為gateway-json-routes,是JSON格式的,里面是路由配置,之所以選擇JSON格式,是因為JSON比yml格式更易於解析和處理;

  • 最終,整個微服務架構如下圖所示:

在這里插入圖片描述

  • 思路已清晰,開始編碼

源碼下載

名稱 鏈接 備注
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) git@github.com:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議
  • 這個git項目中有多個文件夾,本篇的源碼在spring-cloud-tutorials文件夾下,如下圖紅框所示:

在這里插入圖片描述

  • spring-cloud-tutorials是父工程,下屬多個子工程,今天的實戰的代碼是gateway-dynamic-by-nacos,如下圖所示:

在這里插入圖片描述

編碼

  • 新增名為gateway-dynamic-by-nacos的工程,其pom.xml內容如下,注意中文注釋的說明:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-tutorials</artifactId>
        <groupId>com.bolingcavalry</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway-dynamic-by-nacos</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.bolingcavalry</groupId>
            <artifactId>common</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 把springboot內容斷點暴露出去 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- 使用bootstrap.yml的時候,這個依賴一定要有 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>

        <!-- 路由策略使用lb的方式是,這個依賴一定要有 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>

        <!--nacos:配置中心-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <!--nacos:注冊中心-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 如果父工程不是springboot,就要用以下方式使用插件,才能生成正常的jar -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.bolingcavalry.gateway.GatewayApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
  • 配置文件bootstrap.yml,上面只有nacos,可見其他配置信息還是來自naocs:
spring:
  application:
    name: gateway-dynamic-by-nacos
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yml
        group: DEFAULT_GROUP
  • 負責處理進程內路由配置的類是RouteOperator,如下所示,可見整個配置是字符串類型的,用了Jackson的ObjectMapper進行反序列化(注意,前面的實戰中配置文件都是yml格式,但本例中是JSON,稍后在nacos上配置要用JSON格式),然后路由配置的處理主要是RouteDefinitionWriter類型的bean完成的,為了讓配置立即生效,還要用applicationEventPublisher發布進程內消息:
package com.bolingcavalry.gateway.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class RouteOperator {
    private ObjectMapper objectMapper;

    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher applicationEventPublisher;

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

    public RouteOperator(ObjectMapper objectMapper, RouteDefinitionWriter routeDefinitionWriter, ApplicationEventPublisher applicationEventPublisher) {
        this.objectMapper = objectMapper;
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 清理集合中的所有路由,並清空集合
     */
    private void clear() {
        // 全部調用API清理掉
        routeList.stream().forEach(id -> routeDefinitionWriter.delete(Mono.just(id)).subscribe());
        // 清空集合
        routeList.clear();
    }

    /**
     * 新增路由
     * @param routeDefinitions
     */
    private void add(List<RouteDefinition> routeDefinitions) {

        try {
            routeDefinitions.stream().forEach(routeDefinition -> {
                routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
                routeList.add(routeDefinition.getId());
            });
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 發布進程內通知,更新路由
     */
    private void publish() {
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(routeDefinitionWriter));
    }

    /**
     * 更新所有路由信息
     * @param configStr
     */
    public void refreshAll(String configStr) {
        log.info("start refreshAll : {}", configStr);
        // 無效字符串不處理
        if (!StringUtils.hasText(configStr)) {
            log.error("invalid string for route config");
            return;
        }

        // 用Jackson反序列化
        List<RouteDefinition> routeDefinitions = null;

        try {
            routeDefinitions = objectMapper.readValue(configStr, new TypeReference<List<RouteDefinition>>(){});
        } catch (JsonProcessingException e) {
            log.error("get route definition from nacos string error", e);
        }

        // 如果等於null,表示反序列化失敗,立即返回
        if (null==routeDefinitions) {
            return;
        }

        // 清理掉當前所有路由
        clear();

        // 添加最新路由
        add(routeDefinitions);

        // 通過應用內消息的方式發布
        publish();

        log.info("finish refreshAll");
    }
}
  • 做一個配置類RouteOperatorConfig.java,將實例化后的RouteOperator注冊到spring環境中:
package com.bolingcavalry.gateway.config;

import com.bolingcavalry.gateway.service.RouteOperator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RouteOperatorConfig {
    @Bean
    public RouteOperator routeOperator(ObjectMapper objectMapper,
                                       RouteDefinitionWriter routeDefinitionWriter,
                                       ApplicationEventPublisher applicationEventPublisher) {

        return new RouteOperator(objectMapper,
                routeDefinitionWriter,
                applicationEventPublisher);
    }
}

  • 最后是nacos的監聽類RouteConfigListener,可見關鍵技術點是ConfigService.addListener,用於添加監聽,里面就是配置發生變化后更新路由的邏輯,另外還有很重要的一步:立即調用getConfig方法取得當前配置,刷新當前進程的路由配置:
package com.bolingcavalry.gateway.service;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;

@Component
@Slf4j
public class RouteConfigListener {

    private String dataId = "gateway-json-routes";

    private String group = "DEFAULT_GROUP";

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;

    @Autowired
    RouteOperator routeOperator;

    @PostConstruct
    public void dynamicRouteByNacosListener() throws NacosException {

        ConfigService configService = NacosFactory.createConfigService(serverAddr);

        // 添加監聽,nacos上的配置變更后會執行
        configService.addListener(dataId, group, new Listener() {

            public void receiveConfigInfo(String configInfo) {
                // 解析和處理都交給RouteOperator完成
                routeOperator.refreshAll(configInfo);
            }

            public Executor getExecutor() {
                return null;
            }
        });

        // 獲取當前的配置
        String initConfig = configService.getConfig(dataId, group, 5000);

        // 立即更新
        routeOperator.refreshAll(initConfig);
    }
}
  • RouteConfigListener.java中還有一處要記下來,那就是dataId變量的值gateway-json-routes,這是nacos上配置文件的名字,稍后咱們在nacos上配置的時候會用到

  • 最后是平淡無奇的啟動類:

package com.bolingcavalry.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class,args);
    }
}
  • 編碼完成了,接下來在nacos上增加兩個配置;

  • 第一個配置名為gateway-dynamic-by-nacos,內容如下:

server:
  port: 8086

# 暴露端點
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always
  • 第二個配置名為gateway-json-routes,格式要選擇JSON,可見只有一個路由(IP+端口那個),另一個用服務名作為URL的路由先不配上去,稍后用來驗證動態增加能不能立即生效:
[
    {
        "id": "path_route_addr",
        "uri": "http://127.0.0.1:8082",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/hello/**"
                }
            }
        ]
    }
]
  • 至此,咱們已經完成了開發工作,接下來驗證動態路由是否能達到預期效果,我這里用的客戶端工具是postman

驗證

  • 確保nacos、provider-hello、gateway-dynamic-by-nacos等服務全部啟動:

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

  • 在nacos上修改配置項gateway-json-routes的內容,增加名為path_route_lb的路由配置,修改后完整的配置如下:
[
    {
        "id": "path_route_addr",
        "uri": "http://127.0.0.1:8082",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/hello/**"
                }
            }
        ]
    }
    ,
    {
        "id": "path_route_lb",
        "uri": "lb://provider-hello",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/lbtest/**"
                }
            }
        ]
    }
]
  • 點擊右下角的發布按鈕后,gateway-dynamic-by-nacos應用的控制台立即輸出了以下內容,可見監聽已經生效:
2021-08-15 19:39:45.883  INFO 18736 --- [-127.0.0.1_8848] c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [polling-resp] config changed. dataId=gateway-json-routes, group=DEFAULT_GROUP
2021-08-15 19:39:45.883  INFO 18736 --- [-127.0.0.1_8848] c.a.n.client.config.impl.ClientWorker    : get changedGroupKeys:[gateway-json-routes+DEFAULT_GROUP]
2021-08-15 19:39:45.890  INFO 18736 --- [-127.0.0.1_8848] c.a.n.client.config.impl.ClientWorker    : [fixed-127.0.0.1_8848] [data-received] dataId=gateway-json-routes, group=DEFAULT_GROUP, tenant=null, md5=54fb76dcad838917818d0160ce2bd72f, content=[
    {
        "id": "path_route_addr",
        "uri": "http://127.0.0.1:8082",
        "predicates..., type=json
2021-08-15 19:39:45.891  INFO 18736 --- [-127.0.0.1_8848] c.b.gateway.service.RouteOperator        : start refreshAll : [
    {
        "id": "path_route_addr",
        "uri": "http://127.0.0.1:8082",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/hello/**"
                }
            }
        ]
    }
    ,
    {
        "id": "path_route_lb",
        "uri": "lb://provider-hello",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/lbtest/**"
                }
            }
        ]
    }
]
2021-08-15 19:39:45.894  INFO 18736 --- [-127.0.0.1_8848] c.b.gateway.service.RouteOperator        : finish refreshAll
2021-08-15 19:39:45.894  INFO 18736 --- [-127.0.0.1_8848] c.a.nacos.client.config.impl.CacheData   : [fixed-127.0.0.1_8848] [notify-ok] dataId=gateway-json-routes, group=DEFAULT_GROUP, md5=54fb76dcad838917818d0160ce2bd72f, listener=com.bolingcavalry.gateway.service.RouteConfigListener$1@123ae1f6 
2021-08-15 19:39:45.894  INFO 18736 --- [-127.0.0.1_8848] c.a.nacos.client.config.impl.CacheData   : [fixed-127.0.0.1_8848] [notify-listener] time cost=3ms in ClientWorker, dataId=gateway-json-routes, group=DEFAULT_GROUP, md5=54fb76dcad838917818d0160ce2bd72f, listener=com.bolingcavalry.gateway.service.RouteConfigListener$1@123ae1f6 
  • 再用postman發同樣請求,這次終於成功了,可見動態路由已經成功:

在這里插入圖片描述

  • 由於依賴了spring-boot-starter-actuator庫,並且配置文件中也添加了相關配置,我們還可以查看SpringBoot應用內部的配置情況,用瀏覽器訪問http://localhost:8086/actuator/gateway/routes,可見最新的配置情況,如下圖:

在這里插入圖片描述

  • 至此,動態路由的開發和驗證已完成,希望這個實用的功能可以給您一些參考,開發出更加靈活實用的網關服務;

你不孤單,欣宸原創一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 數據庫+中間件系列
  6. DevOps系列

歡迎關注公眾號:程序員欣宸

微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM