前置环境搭建
首先在网关服务中配置好两个服务的路由规则:一个是订单微服务、一个是商品微服务。调用规则是订单微服务调用商品微服务。
server:
port: 8080 #端口
spring:
application:
name: api-gateway-server #服务名称
redis:
host: localhost
pool: 6379
database: 0
cloud: #配置SpringCloudGateway的路由
gateway:
discovery:
locator:
enabled: true #开启根据微服务名称自动转发
lower-case-service-id: true #微服务名称以小写形式呈现
routes:
- id: order-service
uri: lb://service-order
predicates:
- Path=/order-service/**
filters:
- RewritePath=/order-service/(?<segment>.*), /$\{segment}
- id: product-service
uri: lb://service-product
predicates:
- Path=/product-service/**
filters:
- RewritePath=/product-service/(?<segment>.*), /$\{segment}
#eureka注册中心
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/
instance:
prefer-ip-address: true #使用ip地址注册
logging:
level:
root: info
org.springframework.web.servlet.DispatcherServlet: DEBUG
org.springframework.cloud.sleuth: DEBUG
一、引入sleuth坐标
注:
1、在每个调用的服务模块里面都要引入这个坐标。例:网关微服务、订单微服务、商品微服务
<!--sleuth链路追踪-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
2、在以上模块都要开启日志打印
logging:
level:
root: info
org.springframework.web.servlet.DispatcherServlet: DEBUG
org.springframework.cloud.sleuth: DEBUG
测试:
此时在浏览器通过调用网关调用订单微服务,再调用到商品微服务,可以看到控制台会打印和链路追踪相关的日志。
请求路径:localhost:8080/order-service/order/buy/1
网关会根据配置的路由规则自动转发调用到订单微服务