Spring Cloud Gateway如何构建

47次阅读
没有评论

共计 2555 个字符,预计需要花费 7 分钟才能阅读完成。

这篇文章主要介绍“Spring Cloud Gateway 如何构建”的相关知识,丸趣 TV 小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring Cloud Gateway 如何构建”文章能帮助大家解决问题。

构建服务端

  使用 Spring Boot 构建一个简单的 Web 应用,外界向网关发送请求后,会转发到该应用,pom.xml 文件内容如下:

  parent 
  groupId org.springframework.boot /groupId 
  artifactId spring-boot-starter-parent /artifactId 
  version 2.0.2.RELEASE /version 
  /parent 
  dependencies 
  dependency 
  groupId org.springframework.boot /groupId 
  artifactId spring-boot-starter-web /artifactId 
  /dependency 
  /dependencies

  编写启动类与控制器,提供一个“hello”服务:

@SpringBootApplication
@RestController
public class ServerApp { public static void main(String[] args) { SpringApplication.run(ServerApp.class, args);
 }
 @GetMapping(/hello)
 public String hello() {
 System.out.println( 调用  hello  方法 
 return  hello 
 }
}

 ServerApp 中的 hello 方法,会返回 hello 字符串,启动 ServerApp,默认使用 8080 端口,浏览器中访问 http://localhost:8080/hello,可看到浏览器输出结果。

构建网关

  新建一个普通的 Maven 项目,加入 Spring Cloud Gateway 的依赖,pom.xml 内容如下:

  parent 
  groupId org.springframework.boot /groupId 
  artifactId spring-boot-starter-parent /artifactId 
  version 2.0.0.RELEASE /version 
  /parent 
  dependencyManagement 
  dependencies 
  dependency 
  groupId org.springframework.cloud /groupId 
  artifactId spring-cloud-dependencies /artifactId 
  version Finchley.RC1 /version 
  type pom /type 
  scope import /scope 
  /dependency 
  /dependencies 
  /dependencyManagement 
  dependencies 
  dependency 
  groupId org.springframework.cloud /groupId 
  artifactId spring-cloud-starter-gateway /artifactId 
  /dependency 
  /dependencies

  为网关项目加入配置文件 application.yml,修改服务器端口为 9000,配置文件内容如下:

server:
 port: 9000

  添加启动类,配置一个路由定位器的 bean,代码如下:

@SpringBootApplication
public class RouterApp { public static void main(String[] args) { SpringApplication.run(RouterApp.class, args);
 }
 @Bean
 public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { Function PredicateSpec, Route.Builder  fn = new Function PredicateSpec, Route.Builder () { public Route.Builder apply(PredicateSpec t) {
 t.path( /hello 
 return t.uri( http://localhost:8080 
 }
 };
 return builder.routes().route(fn).build();
 }
}

  以上代码中,使用 Spring 容器中的 RouteLocatorBuilder bean 来创建路由定位器,调用 Builder 的 route 方法时,传入 java.util.function.Function 实例,这是 Java8 加入的其中一个函数式接口,我们可以使用函数式编程来实现以上的代码,下面的代码等价于前面的代码:

 @Bean
 public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes()
 .route(t -  t.path( /hello)
 .and()
 .uri(http://localhost:8080))
 .build();
 }

  以上的两段代码设定了一个路由规则,当浏览器访问网关的 http://localhost:9000/hello 地址后,就会路由到 http://localhost:8080/hello。

  除了可以路由到我们本例的 8080 端口外,还可以路由到其他网站,只需要改变一下 PredicateSpec 的 uri 即可,例如将.uri(http://localhost:8080) 改为.uri(“http://www.163.com”)。

关于“Spring Cloud Gateway 如何构建”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注丸趣 TV 行业资讯频道,丸趣 TV 小编每天都会为大家更新不同的知识点。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-04发表,共计2555字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)