十、SpringCloud Sleuth实现请求链路追踪

1、为什么要实现微服务的追踪

    网络非常的脆弱、网络资源非常有限。为数众多的微服务都通过网络进行通信,一个请求都经过了哪些微服务,消耗多长时间,对于解决系统问题很有帮助。

2、SpringCloud Sleuth简介

    Sleuth基本术语:

  • span(跨度):基本工作单元,用一个spanID作为唯一标识。还包含:描述、时间戳事件、span父ID等。初始化的span被称为“root span”,该span的id和trace的ID相等
  • trace(跟踪):一组共享“root span”的span组成的树状结构,用traceID作为唯一标识,trace中所有span共享该traceID
  • annotation(标注):用来记录事件的存在,核心annotation用来定义请求开始和结束

        - CS(Client Sent客户端发送)

        - SR(Server Received服务器端接收):如果用SR减去CS时间戳,得到网络延迟

        - SS(Server Sent服务器端发送):要响应客户端时。如果用SS减去SR,得到服务器端处理请求的时间

        - CR(Client Received客户端接收):客户端接收到响应。如果CR减去CS时间戳,得到客户端发送到最终收到响应总时间

3、整合SpringCloud Sleuth与Zipkin+消息中间件配合使用

    Zipkin可以以前端页面展示的形式更加直观地把整个链路追踪过程展示出来

    Zipkin认会用http协议进行通信,由于网络原因非常不稳定,我们引入消息中间件

    3.1、添加依赖

<dependency>
	<groupId>io.zipkin.java</groupId>
	<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
<dependency>
	<groupId>io.zipkin.java</groupId>
	<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-sleuth-zipkin-stream</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>

    3.2、编写启动类

@SpringBootApplication
@EnableZipkinStreamServer
public class ZipkinServerApplication{
    public static void main(String[] args){
        SpringApplication.run(ZipkinServerApplication.class, args);
    }
}

    3.3、编写配置文件,application.yml

server: 
    port: 9411
spring: 
    rabbitmq: 
        host: localhost
        port: 5672
        username: guest
        password: guest

    启动项目,访问http://localhost:9411/,即可看到一个图形化的操作页面

    3.4、其他微服务的改造

  •         添加依赖
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-sleuth-stream</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-stream-binder-rabbit</artifactId>
</dependency>
  •         修改配置文件application.yml
spring: 
    rabbitmq: 
        host: localhost
        port: 5672
        username: guest
        password: guest

    此时,启动整合后的SleuthServer,启动其他相关微服务,请求微服务即可在http://localhost:9411/看到整个请求链路信息

猜你喜欢

转载自blog.csdn.net/sky_helloword/article/details/86509225