Spring Cloud provides a component for building API gateways on top of Spring WebFlux. Spring Cloud Gateway provides an easy and efficient way to route to APIs and provide them with cross-cutting concerns such as: security, monitoring/metrics and resiliency.
Add Maven dependency
<!-- Springcloud Gateway 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Springcloud Nacos 注册中心依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Springcloud 本地负载均衡依赖,通过注册中心获取服务,需要加入此依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
Configure Gateway
Assertion detailed documentation: https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gateway-request-predicates-factories
Filter detailed documentation: https://docs.spring.io /spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories
server:
port: 8087
spring:
application:
name: gateway-server
cloud:
nacos:
discovery:
server-addr: localhost:8848
group: DEFAULT_GROUP
namespace: public
username: nacos
password: nacos
gateway:
routes:
- id: user-route # 路由ID,唯一标识,自定义命名
uri: lb://gateway-user # 从注册中心获取服务
predicates:
# 路径断言工厂,符合 /user-server 前缀的请求都会被转发
- Path=/user-server/**
filters:
# 去除路径前缀
- StripPrefix=1
# gateway跨域配置
globalcors:
cors-configurations:
'[/**]':
allowed-origins:
- "*"
allowed-methods:
- GET
- POST
- PUT
- DELETE
allowed-headers:
- "*"
allowed-origin-patterns:
- "*"
max-age: 3600
# 设置全局超时时间
httpclient:
connect-timeout: 1000 # 连接超时时间
response-timeout: 5s # 响应超时时间
Access gateway service: http://gateway IP port/user-server/sayhello After
configuring StripPrefix, the first-level path will be removed, and the final gateway forwarding address: http://gateway IP port/sayhello The
request will be forwarded to the configured registration In the gateway-user service of the center.