一、简介
Spring Cloud Gateway 是 Spring Cloud 官方的亲儿子,用来代替 Zuul 网关,两者的区别在于 Zuul 是基于servlet,使用阻塞 API,不支持任何长的连接,如 websocket,Gateway 建立在 Spring 5 ,Spring Boot 2 之上上,使用非阻塞 API。支持Websockets,因为它与 Spring 无缝集成,可以给开发者更好的开发体验。
下面是一个 GateWay 实现路由转发的实例。
二、实例
1、创建服务 gateway-service,eureka-service
核心依赖
<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>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置文件
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
# 根据服务ID查找
enabled: true
routes:
- id: user-route
# uri: http://localhost:8883
uri: lb://user-service
predicates:
- Path=/user-service/**
filters:
# 去掉前缀,转发之前忽略一个前缀,将 /user-service 去掉
- StripPrefix=1
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
server:
port: 8889
2、创建服务 user-service
核心依赖
<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>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
代码
@RestController
public class UserController {
@GetMapping("/admin")
public String admin() {
return "admin";
}
@GetMapping("/guest")
public String guest() {
return "guest";
}
}
yml 配置文件
server:
port: 8883
servlet.context-path: /user
eureka:
client:
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
spring:
application:
name: user-service
三、测试
访问以下网关地址,路由到用户地址
http://localhost:8889/user-service/user/guest
—— 完
看完觉得有用,记得点赞,关注,转发,养成好习惯,拒绝白嫖,从我做起!
ABOUT
公众号:【星尘Pro】
github:https://github.com/huangliangyun
参考资料
https://spring.io/projects/spring-cloud-gateway
https://cloud.spring.io/spring-cloud-gateway/2.2.x/reference/html/
https://cloud.spring.io/spring-cloud-gateway/2.2.x/reference/html/appendix.html
https://cloud.tencent.com/developer/article/1443923