Spring Cloud Gateway 入门
文章首发于公众号《程序员果果》
地址:https://mp.weixin.qq.com/s/wRwq99fNEW4gqgHvR9a-gQ
简介
Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使用阻塞 API,它不支持任何长连接,如 WebSockets。Spring Cloud Gateway 使用非阻塞 API,支持 WebSockets,支持限流等新特性。本文首先用官方的案例带领大家来体验下Spring Cloud的一些简单的功能。
创建工程
创建工程springcloud工程,名为springcloud-gateway-hello
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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gf</groupId>
<artifactId>springcloud-gateway-hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloud-gateway-hello</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
</project>
创建一个简单的路由
Spring Cloud Gateway 使用路由来处理对下游服务的请求。创建RouteLocator的Bean,在本案例将把所有请求路由到 http://httpbin.org。路由可以通过多种方式配置:
@SpringBootApplication
public class SpringcloudGatewayHelloApplication {
public static void main(String[] args) {
SpringApplication.run( SpringcloudGatewayHelloApplication.class, args );
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri("http://httpbin.org:80"))
.build();
}
}
上述myRoutes方法RouteLocatorBuilder可以很容易地用于创建路由。除了创建路由之外,RouteLocatorBuilder还允许你在路由中添加各种 predicates(断言) 和 filters,以便根据特定条件更改请求和响应。
上面创建的route可以让请求“/get”请求都转发到“http://httpbin.org/get”。在route配置上,我们添加了一个filter,该filter会将请求添加一个header,key为hello,value为world。
启动项目,访问http://127.0.0.1:8080/get,显示如下:
{
"args": {
},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,zh-TW;q=0.8",
"Cache-Control": "max-age=0",
"Connection": "close",
"Forwarded": "proto=http;host=\"127.0.0.1:8080\";for=\"127.0.0.1:55607\"",
"Hello": "World",
"Host": "httpbin.org",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"X-Forwarded-Host": "127.0.0.1:8080"
},
"origin": "127.0.0.1, 124.74.78.150",
"url": "http://127.0.0.1:8080/get"
}
可见当向gateway工程请求“/get”,gateway会将工程的请求转发到“http://httpbin.org/get”,并且在转发之前,加上一个filter,该filter会将请求添加一个header,key为hello,value为world。
使用Hystrix
在spring cloud gateway中可以使用Hystrix。Hystrix是 spring cloud中一个服务熔断降级的组件,在微服务系统有着十分重要的作用。
Hystrix 在 spring cloud gateway中是以filter的形式使用的,代码如下:
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/get")
.filters(f -> f.addRequestHeader("Hello", "World"))
.uri("http://httpbin.org:80"))
.route(p -> p
.host("*.hystrix.com")
.filters(f -> f.hystrix(config -> config
.setName("mycmd")
.setFallbackUri("forward:/fallback")))
.uri("http://httpbin.org:80"))
.build();
}
在上面的代码中,我们使用了另外一个router,该router使用host去断言请求是否进入该路由,当请求的host为 “*.hystrix.com”,都会进入该router,该router中有一个hystrix的filter,该filter可以配置名称、和指向性fallback的逻辑的地址,比如本案例中重定向到了“/fallback”。
现在写的一个“/fallback”的l逻辑:
@RequestMapping("/fallback")
public String fallback() {
return "fallback";
}
使用curl执行以下命令:
curl --dump-header - --header 'Host: www.hystrix.com' http://localhost:8080/delay/3
返回的响应为:
HTTP/1.1 200 OK
Content-Type: text/plain;charset=UTF-8
Content-Length: 8
fallback
可见,带host www.hystrix.com 的请求执行了hystrix的fallback的逻辑。
源码
https://github.com/gf-huanchupk/SpringCloudLearning/tree/master/chapter13/springcloud-gateway-hello

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
阿里云图像识别Java调用示例参考
概述 图像识别服务(Image Recognition)基于大数据和深度学习实现,可精准识别图像中的视觉内容,包括上千种物体标签、数十种常见场景等,包含场景分类、图像打标、鉴黄等在线API服务模块,应用于智能相册管理、图片分类和检索、图片安全监控等场景。下面给出使用Java语言分别使用网络图片和本地图片调用场景识别API的示例。 控制台测试 与人脸识别类似,可以参考:阿里云人脸识别使用流程简介 。 Java Code Sample 使用网络图片测试 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConne
-
下一篇
Caused by: com.ctc.wstx.exc.WstxParsingException: Received non-all-whi...
java client 调用webservice, 返回以下错误: 返回message: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"><env:Header/><env:Body><env:Fault>java.lang.Exception: Invalid SOAP formart for xml! 日志: Caused by: com.ctc.wstx.exc.WstxParsingException: Received non-all-whitespace CHARACTERS or CDATA event in nextTag(). at [row,col {unknown-source}]: [3,528] 原因是发送的message中缺少了 <env:Header/> soap envelope schema定义中, header似乎是任意的, 可以没有.
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- CentOS6,CentOS7官方镜像安装Oracle11G
- CentOS关闭SELinux安全模块
- Docker容器配置,解决镜像无法拉取问题
- CentOS7设置SWAP分区,小内存服务器的救世主
- CentOS8编译安装MySQL8.0.19
- MySQL数据库在高并发下的优化方案
- CentOS8,CentOS7,CentOS6编译安装Redis5.0.7
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2初体验,简单认识spring boot2并且搭建基础工程