spring cloud gateway 入门

1
2
3
4
5
6
7
8
9
10
11
<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>

spring-cloud-gateway有两种配置方式,一种是在application.yml中配置,一种是使用@Bean对象注入。(注意:二者选其一)

application.yml方式

1
2
3
4
5
6
7
8
9
10
11
spring:
cloud:
gateway:
routes:
- id: WEB
uri: http://127.0.0.1:8661
predicates:
- Path=/web/{segment}
filters:
- SetPath=/{segment}
- StripPrefix=1

@Bean对象注入配置方式

1
2
3
4
5
6
7
8
@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
  • StripPrefix 去掉转发根据路径web

Zuul VS Gateway

Zuul is built on servlet 2.5 (works with 3.x), using blocking APIs. It doesn’t support any long lived connections, like websockets.

Gateway is built on Spring Framework 5, Project Reactor and Spring Boot 2 using non-blocking APIs. Websockets are supported and it’s a much better developer experience since it’s tightly integrated with Spring.

difference between gateway and zuul