当前位置:   article > 正文

springCloud核心组件之网关(Gateway)_spring gateway

spring gateway

目录

一、Gateway基本使用

1、Gateway定义

2、Gateway作用

3、Gateway的组成

4、Gateway的使用

       1、在以前的项目中创建一个新模块,名叫gateway

       2、导入依赖

       3、配置资源文件

二、路由定义

        一、以服务名的路由

                   资源文件:

        二、以自定义路由

                   资源文件:

三、动态路由设置 

        1、导入依赖

        1、在nacos中新注册一个配置,名叫dynamic-routing.json

        3、导入相关帮助类

        4、进行测试


一、Gateway基本使用

1、Gateway定义

Spring Cloud Gateway是Spring官方基于Spring5.0、SpringBoot2.0和Project Reactor等技术开发的网关,旨在为微服务框架提供一种简单而有效的统一的API路由管理方式,统一访问接口

2、Gateway作用

Spring Cloud Gateway作为Spring Cloud生态体系中的网关,目标是替代Netflix的Zuul,其不仅提供统 一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全、监控/埋点和限流等等。 它是基于Netty的响应式开发模式。

3、Gateway的组成

1️⃣路由(route):路由是网关最基础的部分,路由信息由一个ID,一个目的URL、一组断言工厂和一 组Filter组成。如果断言为真,则说明请求URL和配置的路由匹配。

2️⃣断言(Predicate):Java8中的断言函数,Spring Cloud Gateway中的断言函数输入类型是 Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配 来自http Request中的任何信息,比如请求头和参数等。

3️⃣过滤器(Filter):一个标准的Spring WebFilter,Spring Cloud Gateway中的Filter分为两种类型: Gateway Filter和Global Filter。过滤器Filter可以对请求和响应进行处理。

4、Gateway的使用

       1、在以前的项目中创建一个新模块,名叫gateway

       2、导入依赖

在其中有gataway、nacos、以及loadbalancer的依赖,没有继承父依赖,所以的重新组织依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.zj</groupId>
  6. <artifactId>gateway</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>gateway</name>
  9. <description>gateway</description>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. <maven.compiler.source>1.7</maven.compiler.source>
  13. <maven.compiler.target>1.7</maven.compiler.target>
  14. <spring-boot.version>2.4.1</spring-boot.version>
  15. <spring-cloud.version>2020.0.0</spring-cloud.version>
  16. <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-webflux</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.cloud</groupId>
  34. <artifactId>spring-cloud-starter-gateway</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-actuator</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.alibaba.cloud</groupId>
  42. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.cloud</groupId>
  46. <artifactId>spring-cloud-loadbalancer</artifactId>
  47. </dependency>
  48. </dependencies>
  49. <dependencyManagement>
  50. <dependencies>
  51. <dependency>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-dependencies</artifactId>
  54. <version>${spring-boot.version}</version>
  55. <type>pom</type>
  56. <scope>import</scope>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework.cloud</groupId>
  60. <artifactId>spring-cloud-dependencies</artifactId>
  61. <version>${spring-cloud.version}</version>
  62. <type>pom</type>
  63. <scope>import</scope>
  64. </dependency>
  65. <dependency>
  66. <groupId>com.alibaba.cloud</groupId>
  67. <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  68. <version>${spring-cloud-alibaba.version}</version>
  69. <type>pom</type>
  70. <scope>import</scope>
  71. </dependency>
  72. </dependencies>
  73. </dependencyManagement>
  74. <build>
  75. <plugins>
  76. <plugin>
  77. <groupId>org.apache.maven.plugins</groupId>
  78. <artifactId>maven-compiler-plugin</artifactId>
  79. <version>3.8.1</version>
  80. <configuration>
  81. <source>1.8</source>
  82. <target>1.8</target>
  83. <encoding>UTF-8</encoding>
  84. </configuration>
  85. </plugin>
  86. <plugin>
  87. <groupId>org.springframework.boot</groupId>
  88. <artifactId>spring-boot-maven-plugin</artifactId>
  89. <version>2.4.1</version>
  90. <configuration>
  91. <mainClass>com.zj.gateway.GatewayApplication</mainClass>
  92. </configuration>
  93. <executions>
  94. <execution>
  95. <id>repackage</id>
  96. <goals>
  97. <goal>repackage</goal>
  98. </goals>
  99. </execution>
  100. </executions>
  101. </plugin>
  102. </plugins>
  103. </build>
  104. </project>

       3、配置资源文件

server:
  #此处的8084端口号,就好像以前外置的tomcat的8080,让我们通过浏览器进行访问
  #但此服务只是做了一个路由,它会将请求路由到其它微服务(一般是消费者)进行处理
  port: 8085

spring:
  application:
    #微服务名
    name: gateway
  cloud:
    nacos:
      discovery:
        #指定nacos注册中心的地址
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          #是否与服务发现组件进行结合,通过service-id(必须设置成大写)转发到具体的服务实例。默认false
          #为true代表开启基于服务发现的路由规则。
          enabled: false
          #配置之后访问时service-id无需大写
          lower-case-service-id: true
      routes:
        # 路由标识(id:标识,具有唯一性)
        - id: user-consumer-api
          #目标服务地址(uri:地址,请求转发后的地址),会自动从注册中心获得服务的IP,不需要手动写死
          uri: lb://consumer
          #优先级,越小越优先
          #order: 999
          #路由条件(predicates:断言)
          predicates:
            # 路径匹配,
            - Path=/cum/**
          filters:
            #路径前缀删除示例:请求/name/bar/foo,StripPrefix=2,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo
            #前缀过滤,请求地址:http://localhost:8084/usr/hello
            #此处配置去掉1个路径前缀,再配置上面的 Path=/usr/**,就将**转发到指定的微服务
            #因为这个api相当于是服务名,只是为了方便以后nginx的代码加上去的,对于服务提供者service-client来说,不需要这段地址,所以需要去掉
            - StripPrefix=1
        # 路由标识(id:标识,具有唯一性)
        - id: user-provider-api
          #目标服务地址(uri:地址,请求转发后的地址),会自动从注册中心获得服务的IP,不需要手动写死
          uri: lb://provider
          #优先级,越小越优先
          #order: 999
          #路由条件(predicates:断言)
          predicates:
            # 路径匹配,
            - Path=/api/pro/**
          filters:
            #路径前缀删除示例:请求/name/bar/foo,StripPrefix=2,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo
            #前缀过滤,请求地址:http://localhost:8084/usr/hello
            #此处配置去掉1个路径前缀,再配置上面的 Path=/usr/**,就将**转发到指定的微服务
            #因为这个api相当于是服务名,只是为了方便以后nginx的代码加上去的,对于服务提供者service-client来说,不需要这段地址,所以需要去掉
            - StripPrefix=2
logging:
  level:
    #开启spring-Cloud-gateway的日志级别为debug,方便debug调试
    org.springframework.cloud.gateway: trace
    org.springframework.http.server.reactive: debug
    org.springframework.web.reactive: debug
    reactor.ipc.netty: debug
#springboot监控Actuator,暴露所有端点
management:
  endpoints:
    web:
      exposure:
        include: '*'
#自定义配置
gateway:
  nacos:
    server-addr: ${spring.cloud.nacos.discovery.server-addr}
    # namespace: xxx-xx-xx-xx
    data-id: dynamic-routing.json
    group: DEFAULT_GROUP

二、路由定义

        一、以服务名的路由

                   资源文件:

gateway:
  discovery:
    locator:
      #是否与服务发现组件进行结合,通过service-id(必须设置成大写)转发到具体的服务实例。默认false
      #为true代表开启基于服务发现的路由规则。
      enabled: true
      #配置之后访问时service-id无需大写
      lower-case-service-id: true

        二、以自定义路由

                   资源文件:

gateway:
  discovery:
    locator:
      #是否与服务发现组件进行结合,通过service-id(必须设置成大写)转发到具体的服务实例。默认false
      #为true代表开启基于服务发现的路由规则。
      enabled: false
      #配置之后访问时service-id无需大写
      lower-case-service-id: true
  routes:
    # 路由标识(id:标识,具有唯一性)
    - id: user-consumer-api
      #目标服务地址(uri:地址,请求转发后的地址),会自动从注册中心获得服务的IP,不需要手动写死
      uri: lb://consumer
      #优先级,越小越优先
      #order: 999
      #路由条件(predicates:断言)
      predicates:
        # 路径匹配,
        - Path=/cum/**
      filters:
        #路径前缀删除示例:请求/name/bar/foo,StripPrefix=2,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo
        #前缀过滤,请求地址:http://localhost:8084/usr/hello
        #此处配置去掉1个路径前缀,再配置上面的 Path=/usr/**,就将**转发到指定的微服务
        #因为这个api相当于是服务名,只是为了方便以后nginx的代码加上去的,对于服务提供者service-client来说,不需要这段地址,所以需要去掉
        - StripPrefix=1
    # 路由标识(id:标识,具有唯一性)
    - id: user-provider-api
      #目标服务地址(uri:地址,请求转发后的地址),会自动从注册中心获得服务的IP,不需要手动写死
      uri: lb://provider
      #优先级,越小越优先
      #order: 999
      #路由条件(predicates:断言)
      predicates:
        # 路径匹配,
        - Path=/api/pro/**
      filters:
        #路径前缀删除示例:请求/name/bar/foo,StripPrefix=2,去除掉前面两个前缀之后,最后转发到目标服务的路径为/foo
        #前缀过滤,请求地址:http://localhost:8084/usr/hello
        #此处配置去掉1个路径前缀,再配置上面的 Path=/usr/**,就将**转发到指定的微服务
        #因为这个api相当于是服务名,只是为了方便以后nginx的代码加上去的,对于服务提供者service-client来说,不需要这段地址,所以需要去掉
        - StripPrefix=2

enabled: false后的测试: 

三、动态路由设置 

        1、导入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.zj</groupId>
  6. <artifactId>gateway</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>gateway</name>
  9. <description>gateway</description>
  10. <properties>
  11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  12. <maven.compiler.source>1.7</maven.compiler.source>
  13. <maven.compiler.target>1.7</maven.compiler.target>
  14. <spring-boot.version>2.4.1</spring-boot.version>
  15. <spring-cloud.version>2020.0.0</spring-cloud.version>
  16. <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-webflux</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.cloud</groupId>
  34. <artifactId>spring-cloud-starter-gateway</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-actuator</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.alibaba.cloud</groupId>
  42. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework.cloud</groupId>
  46. <artifactId>spring-cloud-loadbalancer</artifactId>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.projectlombok</groupId>
  50. <artifactId>lombok</artifactId>
  51. </dependency>
  52. <dependency>
  53. <groupId>com.alibaba</groupId>
  54. <artifactId>fastjson</artifactId>
  55. <version>1.2.35</version>
  56. </dependency>
  57. </dependencies>
  58. <dependencyManagement>
  59. <dependencies>
  60. <dependency>
  61. <groupId>org.springframework.boot</groupId>
  62. <artifactId>spring-boot-dependencies</artifactId>
  63. <version>${spring-boot.version}</version>
  64. <type>pom</type>
  65. <scope>import</scope>
  66. </dependency>
  67. <dependency>
  68. <groupId>org.springframework.cloud</groupId>
  69. <artifactId>spring-cloud-dependencies</artifactId>
  70. <version>${spring-cloud.version}</version>
  71. <type>pom</type>
  72. <scope>import</scope>
  73. </dependency>
  74. <dependency>
  75. <groupId>com.alibaba.cloud</groupId>
  76. <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  77. <version>${spring-cloud-alibaba.version}</version>
  78. <type>pom</type>
  79. <scope>import</scope>
  80. </dependency>
  81. </dependencies>
  82. </dependencyManagement>
  83. <build>
  84. <plugins>
  85. <plugin>
  86. <groupId>org.apache.maven.plugins</groupId>
  87. <artifactId>maven-compiler-plugin</artifactId>
  88. <version>3.8.1</version>
  89. <configuration>
  90. <source>1.8</source>
  91. <target>1.8</target>
  92. <encoding>UTF-8</encoding>
  93. </configuration>
  94. </plugin>
  95. <plugin>
  96. <groupId>org.springframework.boot</groupId>
  97. <artifactId>spring-boot-maven-plugin</artifactId>
  98. <version>2.4.1</version>
  99. <configuration>
  100. <mainClass>com.zj.gateway.GatewayApplication</mainClass>
  101. </configuration>
  102. <executions>
  103. <execution>
  104. <id>repackage</id>
  105. <goals>
  106. <goal>repackage</goal>
  107. </goals>
  108. </execution>
  109. </executions>
  110. </plugin>
  111. </plugins>
  112. </build>
  113. </project>

        1、在nacos中新注册一个配置,名叫dynamic-routing.json

  1. {
  2. "refreshGatewayRoute": true,
  3. "routeList": [
  4. {
  5. "id": "consumer-api",
  6. "predicates": [
  7. {
  8. "name": "Path",
  9. "args": {
  10. "_genkey_0": "/cum/**"
  11. }
  12. }
  13. ],
  14. "filters": [
  15. {
  16. "name": "StripPrefix",
  17. "args": {
  18. "_genkey_0": "1"
  19. }
  20. }
  21. ],
  22. "uri": "lb://consumer",
  23. "order": 0
  24. },
  25. {
  26. "id": "provider-api",
  27. "predicates": [
  28. {
  29. "name": "Path",
  30. "args": {
  31. "_genkey_0": "/ccc/prv/**"
  32. }
  33. }
  34. ],
  35. "filters": [
  36. {
  37. "name": "StripPrefix",
  38. "args": {
  39. "_genkey_0": "2"
  40. }
  41. }
  42. ],
  43. "uri": "lb://provider",
  44. "order": 0
  45. }
  46. ]
  47. }

        3、导入相关帮助类

DynamicRoutingConfig:
  1. package com.zj.gateway;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.alibaba.nacos.api.NacosFactory;
  5. import com.alibaba.nacos.api.PropertyKeyConst;
  6. import com.alibaba.nacos.api.config.ConfigService;
  7. import com.alibaba.nacos.api.config.listener.Listener;
  8. import com.alibaba.nacos.api.exception.NacosException;
  9. import com.fasterxml.jackson.databind.ObjectMapper;
  10. import com.zj.gateway.pojo.FilterEntity;
  11. import com.zj.gateway.pojo.GatewayNacosProperties;
  12. import com.zj.gateway.pojo.PredicateEntity;
  13. import com.zj.gateway.pojo.RouteEntity;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
  17. import org.springframework.cloud.gateway.filter.FilterDefinition;
  18. import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
  19. import org.springframework.cloud.gateway.route.RouteDefinition;
  20. import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
  21. import org.springframework.context.ApplicationEventPublisher;
  22. import org.springframework.context.ApplicationEventPublisherAware;
  23. import org.springframework.context.annotation.Bean;
  24. import org.springframework.stereotype.Component;
  25. import org.springframework.web.util.UriComponentsBuilder;
  26. import reactor.core.publisher.Mono;
  27. import java.net.URI;
  28. import java.util.ArrayList;
  29. import java.util.List;
  30. import java.util.Properties;
  31. import java.util.concurrent.Executor;
  32. /**
  33. * 此类实现了Spring Cloud Gateway + nacos 的动态路由,
  34. * 它实现一个Spring提供的事件推送接口ApplicationEventPublisherAware
  35. */
  36. @SuppressWarnings("all")
  37. @Slf4j
  38. @Component
  39. public class DynamicRoutingConfig implements ApplicationEventPublisherAware {
  40. @Autowired
  41. private RouteDefinitionWriter routeDefinitionWriter;
  42. @Autowired
  43. private GatewayNacosProperties gatewayProperties;
  44. @Autowired
  45. private ObjectMapper mapper;
  46. private ApplicationEventPublisher applicationEventPublisher;
  47. @Override
  48. public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
  49. this.applicationEventPublisher = applicationEventPublisher;
  50. }
  51. /**
  52. * 这个方法主要负责监听Nacos的配置变化,这里先使用参数构建一个ConfigService,
  53. * 再使用ConfigService开启一个监听,
  54. * 并且在监听的方法中刷新路由信息。
  55. */
  56. @Bean
  57. public void refreshRouting() throws NacosException {
  58. //创建Properties配置类
  59. Properties properties = new Properties();
  60. System.out.println(gatewayProperties);
  61. //设置nacos的服务器地址,从配置类GatewayProperties中获取
  62. properties.put(PropertyKeyConst.SERVER_ADDR, gatewayProperties.getServerAddr());
  63. //设置nacos的命名空间,表示从具体的命名空间中获取配置信息,不填代表默认从public获得
  64. if (gatewayProperties.getNamespace() != null) {
  65. properties.put(PropertyKeyConst.NAMESPACE, gatewayProperties.getNamespace());
  66. }
  67. //根据Properties配置创建ConfigService类
  68. ConfigService configService = NacosFactory.createConfigService(properties);
  69. //获得nacos中已有的路由配置
  70. String json = configService.getConfig(gatewayProperties.getDataId(), gatewayProperties.getGroup(), 5000);
  71. if(json==null) {
  72. return;
  73. }
  74. this.parseJson(json);
  75. //添加监听器,监听nacos中的数据修改事件
  76. configService.addListener(gatewayProperties.getDataId(), gatewayProperties.getGroup(), new Listener() {
  77. @Override
  78. public Executor getExecutor() {
  79. return null;
  80. }
  81. /**
  82. * 用于接收远端nacos中数据修改后的回调方法
  83. */
  84. @Override
  85. public void receiveConfigInfo(String configInfo) {
  86. log.warn(configInfo);
  87. //获取nacos中修改的数据并进行转换
  88. parseJson(configInfo);
  89. }
  90. });
  91. }
  92. /**
  93. * 解析从nacos读取的路由配置信息(json格式)
  94. */
  95. public void parseJson(String json) {
  96. log.warn("从Nacos返回的路由配置(JSON格式):" + json);
  97. boolean refreshGatewayRoute = JSONObject.parseObject(json).getBoolean("refreshGatewayRoute");
  98. if (refreshGatewayRoute) {
  99. List<RouteEntity> list = JSON.parseArray(JSONObject.parseObject(json).getString("routeList")).toJavaList(RouteEntity.class);
  100. for (RouteEntity route : list) {
  101. update(assembleRouteDefinition(route));
  102. }
  103. } else {
  104. log.warn("路由未发生变更");
  105. }
  106. }
  107. /**
  108. * 路由更新
  109. */
  110. public void update(RouteDefinition routeDefinition) {
  111. try {
  112. this.routeDefinitionWriter.delete(Mono.just(routeDefinition.getId()));
  113. log.warn("路由删除成功:" + routeDefinition.getId());
  114. } catch (Exception e) {
  115. log.error(e.getMessage(), e);
  116. }
  117. try {
  118. routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
  119. this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
  120. log.warn("路由更新成功:" + routeDefinition.getId());
  121. } catch (Exception e) {
  122. log.error(e.getMessage(), e);
  123. }
  124. }
  125. /**
  126. * 路由定义
  127. */
  128. public RouteDefinition assembleRouteDefinition(RouteEntity routeEntity) {
  129. RouteDefinition definition = new RouteDefinition();
  130. // ID
  131. definition.setId(routeEntity.getId());
  132. // Predicates
  133. List<PredicateDefinition> pdList = new ArrayList<>();
  134. for (PredicateEntity predicateEntity : routeEntity.getPredicates()) {
  135. PredicateDefinition predicateDefinition = new PredicateDefinition();
  136. predicateDefinition.setArgs(predicateEntity.getArgs());
  137. predicateDefinition.setName(predicateEntity.getName());
  138. pdList.add(predicateDefinition);
  139. }
  140. definition.setPredicates(pdList);
  141. // Filters
  142. List<FilterDefinition> fdList = new ArrayList<>();
  143. for (FilterEntity filterEntity : routeEntity.getFilters()) {
  144. FilterDefinition filterDefinition = new FilterDefinition();
  145. filterDefinition.setArgs(filterEntity.getArgs());
  146. filterDefinition.setName(filterEntity.getName());
  147. fdList.add(filterDefinition);
  148. }
  149. definition.setFilters(fdList);
  150. // URI
  151. URI uri = UriComponentsBuilder.fromUriString(routeEntity.getUri()).build().toUri();
  152. definition.setUri(uri);
  153. return definition;
  154. }
  155. }
pojo--->FilterEntity
  1. package com.zj.gateway.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import lombok.experimental.Accessors;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8. /**
  9. * @author zj
  10. */
  11. @SuppressWarnings("all")
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @Accessors(chain = true)
  16. public class FilterEntity {
  17. //过滤器对应的Name
  18. private String name;
  19. //路由规则
  20. private Map<String, String> args = new LinkedHashMap<>();
  21. }
pojo--->GatewayNacosProperties
  1. package com.zj.gateway.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import lombok.experimental.Accessors;
  6. import org.springframework.boot.context.properties.ConfigurationProperties;
  7. import org.springframework.stereotype.Component;
  8. @SuppressWarnings("all")
  9. @Data
  10. @NoArgsConstructor
  11. @AllArgsConstructor
  12. @Accessors(chain = true)
  13. @ConfigurationProperties(prefix = "gateway.nacos")
  14. @Component
  15. public class GatewayNacosProperties {
  16. private String serverAddr;
  17. private String dataId;
  18. private String namespace;
  19. private String group;
  20. }
pojo--->PredicateEntity
  1. package com.zj.gateway.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import lombok.experimental.Accessors;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8. /**
  9. * @author zj
  10. */
  11. @SuppressWarnings("all")
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @Accessors(chain = true)
  16. public class PredicateEntity {
  17. //断言对应的Name
  18. private String name;
  19. //断言规则
  20. private Map<String, String> args = new LinkedHashMap<>();
  21. }
pojo--->RouteEntity
  1. package com.zj.gateway.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import lombok.experimental.Accessors;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. /**
  9. * @author hgh
  10. */
  11. @SuppressWarnings("all")
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @Accessors(chain = true)
  16. public class RouteEntity {
  17. //路由id
  18. private String id;
  19. //路由断言集合
  20. private List<PredicateEntity> predicates = new ArrayList<>();
  21. //路由过滤器集合
  22. private List<FilterEntity> filters = new ArrayList<>();
  23. //路由转发的目标uri
  24. private String uri;
  25. //路由执行的顺序
  26. private int order = 0;
  27. }

        4、进行测试

 当我在配置中修改路径之后就访问不到了

这就实现了动态路由

今天的知识就分享到这了,希望能够帮助到你! 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/301431
推荐阅读
相关标签
  

闽ICP备14008679号