初识SpringCloud系列——Sleuth原理

这是我参与更文挑战的第24天,活动详情查看: 更文挑战

前言

随着服务越来越多,彼此间的关系也日渐复杂:A->B;B->C;C->D;D->A+B.....这么多服务,当某个服务出现问题,我们能够知道这个服务出问题了,但问题是出在服务本身,还是处在服务调用的下一个服务身上,梳理服务之间的关系,定位问题变的十分困难,这时,它出现在灯火阑珊处————Spring Cloud Sleuth

什么是Spring Cloud Sleuth?

Spring Cloud Sleuth 为分布式跟踪提供 Spring Boot 自动配置,Sleuth 配置了您开始所需的一切。 这包括跟踪数据(跨度)报告到哪里、要保留多少跟踪(采样)、是否发送远程字段(行李)以及跟踪哪些库。————摘自官网

  • Spring Cloud Sleuth提供了一套完整的服务跟踪的解决方
  • 在分布式系统中提供追踪解决方案并且兼容支持了zipkin

Spring Cloud Sleuth能追踪哪些组件?

  • async
  • Hystrix
  • messaging:message原理可参考
  • websocket
  • rxjava
  • scheduling
  • web(Spring MVC Controller,Servlet)
  • webclient(Spring RestTemplate)
  • Feign
  • Zuul

Spring Cloud Sleuth的实现逻辑?

  • span:表示调用链路来源,通俗的理解span就是一次请求信息
  • Trace:类似于树结构的Span集合,表示一条调用链路,存在唯一标识
  • Annotation:用来及时记录一个事件的存在
    • Client Sent -客户端发起一个请求
    • Server Received -服务端获得请求并准备开始处理它(加入Client Sent时间能能计算出网络延迟时间)
    • Server Sent -注解表明请求处理的完成(加入Server Received时间能计算出到服务端的处理请求时间)

表示一请求链路,一条链路通过Trace ld唯一标识,Span标识发起的请求信息,各span通过parent id关联起来
image.png
—条链路通过Trace ld唯一标识,Span标识发起的请求信息,各span通过parent id关联起来。

image.png
使用?
使用Sleuth,那么需要结合Zipkin Server(F版之后不要要自己搭建Zipkin Server)一起,只要直接运行对应版本的jar包就行

java -jar zipkin-server-2.12.9-exec.jar
复制代码

实现
provider服务
pom加入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
复制代码

在yml文件中的spring下一级中加入对应的配置信息

spring:
  application:
    name: cloud-stream-provider
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
    #采样率值介于 0 到 1 之间,1 则表示全部采集
    probability: 1
复制代码

consumer服务
pom中一个加入zipkin依赖,yml文件中也是加入zipkin对应的配置

spring:
  application:
    name: cloud-stream-consumer
  zipkin:
    base-url: http://localhost:9411
  sleuth:
    sampler:
    #采样率值介于 0 到 1 之间,1 则表示全部采集
    probability: 1    
复制代码

然后启动服务,调用consumer服务————>provider服务,zipkin页面则会出现对应的数据

zipkin页面详解

image.png
image.png

今日小结

今日主要大致了解了Sleuth的作用,Sleuth的内部原理以及Sleuth的简单使用,好了,今天就到这啦,再见!