Spring Cloud Gateway(三)
之前用 client-service
模拟客户端发起请求,此篇通过网关模拟客户端发起请求。
Spring Cloud Gateway 改写之前 client-service
调用 product
Gateway加入链路追踪
<!-- 链路依赖 start -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
<!-- 链路依赖 end -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
配置Gateway路由负载均衡转发
application.yml 更新
Spring:
zipkin:
base-url: http://192.168.79.8:9411
sender:
type: rabbit
sleuth:
sampler:
# 全部采样
probability: 1.0
rabbitmq:
host: 192.168.79.8
port: 5672
username: admin
password: admin
cloud:
nacos:
discovery:
server-addr: 192.168.79.8:9999
service: ${spring.application.name}
# 此处需要额外注意,group 的值需与相关路由转发均衡负载的服务 如 `product-service` 配置的相同,否则会找不到相关服务
group: provider-consumer
gateway:
routes:
- id: product-route
uri: lb://product-service
predicates:
- Path=/api/productServ/**
filters:
- StripPrefix=2
验证
发起请求
http://localhost:8080/api/productServ/product/2
http://localhost:8080/api/productServ/products
注意
Spring Cloud Gateway Nacos 配置可能出现问题
- nacos 服务如果配置了分组,需将各服务间调用如果使用负载均衡
url: lb://${serviceName}
格式,需配置相同的分组,否则无法找到对应的目标服务
- 引入
uri: lb://${serviceName}
需引入依赖包spring-cloud-loadbalancer
- 出现警告
LoadBalancerCacheManager not available, returning delegate without caching.
需引入caffeine
,spring-context-support