微服务与中间件——GateWay网关
GateWay
SpringCloudGateway则是 基于Spring5中提供的WebFlux,属于响应
式编程的实现,具备更好的性能
为什么需要网关
- 进行身份验证、权限校验
- 进行服务路由、负载均衡
- 请求限流
QuickStart
准备工作
该项目依赖nacos+feign,这两个配好是前提条件,若有问题请查看:微服务与中间件系列——Feign
1.构建一个新服务
2.引入依赖
注意一定要加上loadBalanced依赖,因为新版本中已经去除了Ribbon的负载所以我们要引入
否则会有There was an unexpected error (type=Service Unavailable, status=503)
报错提示
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
3.修改yaml
server:
port: 8899
spring:
application:
name: gateway
cloud:
nacos:
server-addr: localhost:8848
gateway:
routes: # 网关路由配置
- id: test-service # 自定义路由id,必须唯一
uri: lb://userService # 路由的目标地址,lb表示loadbalance负载均衡,后://服务名