SpringCloud -GateWay

别等时光非礼了梦想. 提交于 2019-12-11 16:28:46

一,简单的示例 入门

参考地址:http://www.ityouknow.com/spring-cloud

1.1 pom.xml

使用 Spring Cloud Finchley 版本,Finchley 版本依赖于 Spring Boot 2.0.6.RELEASE。

  <parent>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-parent</artifactId>      <version>2.0.6.RELEASE</version>      <relativePath/> <!-- lookup parent from repository -->  </parent>  ​  <dependencyManagement>      <dependencies>          <dependency>              <groupId>org.springframework.cloud</groupId>              <artifactId>spring-cloud-dependencies</artifactId>              <version>Finchley.SR2</version>              <type>pom</type>              <scope>import</scope>          </dependency>      </dependencies>  </dependencyManagement>

项目需要使用的依赖包

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

Spring Cloud Gateway 是使用 netty+webflux 实现因此不需要再引入 web 模块。

1.2 Spring Cloud Gateway 网关路由有两种配置方式:

1.2.1 第一种如下在配置文件 yml 中配置

入门application.yml配置

    server:    port: 8083  spring:    cloud:      gateway:        routes:        - id: 1          uri: http://www.ityouknow.com          predicates:          - Path=/spring-cloud

各字段含义如下:

  • id:我们自定义的路由 ID,保持唯一

  • uri:目标服务地址

  • predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。

  • filters:过滤规则,本示例暂时没用。

上面这段配置的意思是,配置了一个 id 为 1的路由规则,当访问地址 http://localhost:8083/spring-cloud时会自动转发到地址:http://www.ityouknow.com/spring-cloud。配置完成启动项目即可在浏览器访问进行测试,当我们访问地址http://localhost:8083/spring-cloud 时会展示页面展示如下:

 

 

 

1.2.2 第二种通过@Bean自定义 RouteLocator,如下在启动类 GateWayApplication 中添加方法 customRouteLocator() 来定制转发规则。
    @SpringBootApplication  ​  public class App {  ​      public static void main( String[] args ){  ​          SpringApplication.run(App.class, args);  ​      }      @Bean      public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {          return builder.routes()              .route("2", r -> r.path("/about")                      .uri("http://ityouknow.com"))              .build();      }  }

 

 

上面配置了一个 id 为2 的路由,当访问地址http://localhost:8083/about时会自动转发到地址:http://www.ityouknow.com/about和上面的转发效果一样,只是这里转发的是以项目地址/about格式的请求地址。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!