Cloud(六) —— Spring Cloud Gateway与zuul使用对比"/>
青柠开车Spring Cloud(六) —— Spring Cloud Gateway与zuul使用对比
青柠开车Spring cloud(一) —— 生态系统以及在企业项目中的基础架构图 (1-7),有时间可以看看
项目源码github地址
- 补充
Gateway
简介- 快速入门
Gateway
项目基本配置- 加入gateway网关配置
- 集成
Eureka
补充
-
使用网关前项目架构
 -
使用网关后项目架构

Gateway
简介
官方文档、官方demo
spring-cloud-Gateway
是spring-cloud
的一个子项目。而zuul
则是netflix
公司的项目,只是spring将zuul
集成在spring-cloud中使用而已。
还有一种说法是因为zuul2
连续跳票和zuul1
的性能表现不是很理想,所以催生了spring孵化Gateway
项目。
快速入门
在spring-cloud
创建spring-cloud-gateway
子模块项目
Gateway
项目基本配置
- 在
pom.xml
中加入jar包
<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- 集成eureka --><!--<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>-->
</dependencies>
application.properties
配置
server.port= 8562
spring.application.name=gateway# 日志打印的级别
logging.level.org.springframework.cloud.gateway = debug#集成eureka时开启
#spring.cloud.gateway.discovery.locator.enabled=true
#集成eureka
#eureka.client.serviceUrl.defaultZone= http://localhost:8761/eureka/
springboot
启动类
/*** @author : R&M www.rmworking.com/blog* 2018/9/18 11:15* spring-cloud* org.qnloft.gateway*/
//@EnableEurekaClient
@SpringBootApplication
public class GateWayApplication {public static void main(String[] args) throws Exception {SpringApplication.run(GateWayApplication.class, args);}
}
加入gateway网关配置
看完上面的内容,小伙伴们应该发现,这和普通的springboot项目有毛区别啊~~~,别着急,让我带领大家来揭开gateway的面纱!
spring-cloud-gateway
有两种配置方式,一种是在application.yml
中配置,一种是使用@Bean
对象注入。(注意:二者选其一)
application.yml
方式
spring:cloud:gateway:routes:- id: WEBuri: http://127.0.0.1:8661predicates:- Path=/web/{segment}filters:- SetPath=/{segment}
@Bean
对象注入配置方式
在GateWayApplication.java
中加入如下内容:
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {return builder.routes().route("WEB", r -> r.path("/web/{segment}").filters(f -> f.setPath("/{segment}")).uri("http://127.0.0.1:8661")).build();
}
简要说明:
id
:路由的id,参数配置不要重复,如不配置,gateway会使用生成一个uuid代替。uri
:路由的目标地址。注意:uri地址后面不要加 " / "Path
:配置路由的路径。比如:/web/{segment}
则表示当访问http://127.0.0.1:8562/web/**
时候路由的指定的uri上面- SetPath:在发起请求时,在路由请求路径后面加上
web/
后面的内容。如果不配置,将无法路由地址后缀/web/index
,只能路由/web
测试:现在我们启动spring-web
项目和spring-cloud-gateway
项目,浏览器访问:http://127.0.0.1:8562/web/index ,当出现和 http://127.0.0.1:8661/index 相同的内容既证明网关配置成功。
关于@Bean
方式更多配置请参见:这里
集成Eureka
将项目的注释部分解注,即可成功集成。
更多推荐
青柠开车Spring Cloud(六) —— Spring Cloud Gateway与zuul使用对比
发布评论