Unified Gateway Gateway
1 The role of the gateway
1. Perform identity authentication and authority verification on user requests
2. Route user requests to microservices and implement load balancing
3. Limit the flow of user requests to prevent microservices from crashing due to excessive concurrency
2. Build gateway service
Create a new module, import SpringCloudGateway dependencies and nacos service discovery dependencies
Because Gateway itself is also a microservice, it needs to be registered in nacos and discovered by nacos
<!--nacos的服务发现依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 网关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Write routing configuration and nacos address:
Routing configuration includes
1. Route id: the unique identifier of the route
2. Routing target: the target address of the route, lb means load balancing according to the service name
3. Routing assertion: judging routing rules
4. Route filter: process the request or response
server:
port: 10010
spring:
application:
name: gateway #服务名称
cloud:
nacos:
server-addr: localhost:8848 #nacos地址
gateway:
routes: #网关的路由配置
- id: user-service #路由id 可自定义但要保证唯一性
uri: lb://userservice #路由的目标地址
predicates: #判断请求是否符合路由规则的条件
- Path=/user/**
- id: order-service #路由id 可自定义但要保证唯一性
uri: lb://orderservice #路由的目标地址
predicates: #判断请求是否符合路由规则的条件
- Path=/order/**
Access 10010/order/101, successfully obtain data, indicating that gateway routing is successful