spring cloud-sleuth原理浅析

本文基于sleuth 2.2.5版本

sleuth是一个链路追踪工具,通过它在日志中打印的信息可以分析出一个服务的调用链条,也可以得出链条中每个服务的耗时,这为我们在实际生产中,分析超时服务,分析服务调用关系,做服务治理提供帮助。
第一次使用sleuth,虽说跟着网上的教程也可以运行出正确的结果,但是对于原理、更进一步的使用还是一头蒙。我就尝试着分析一下源代码,其代码量并不大,但是代码还真是难懂,看了一段时间源码,并从网上找了资料,只是对原理、部分类的作用有了一些了解,我通过本文做一下介绍。

文章目录

 

一、概念介绍

先说几个概念。
span:span是sleuth中最基本的工作单元,一个微服务收到请求后会创建一个span同时产生一个span id,span id是一个64位的随机数,sleuth将其转化为16进制的字符串,打印在日志里面。其对应的实现类是RealSpan。
trace id:在一个调用链条中,trace id是始终不变的,每经过一个微服务span id生成一个新的,所以通过trace id可以找出调用链上所有经过的微服务。trace id默认是64位,可以通过spring.sleuth.traceId128=true设置trace id为128位。调用链的第一个服务,其span id和trace id是同一个值。

sleuth目前并不是对所有调用访问都可以做链路追踪,它目前支持的有:rxjava、feign、quartz、RestTemplate、zuul、hystrix、grpc、kafka、Opentracing、redis、Reator、circuitbreaker、spring的Scheduled。国内用的比较多的dubbo,sleuth无法对其提供支持。

二、场景描述

本文以http访问介绍一下sleuth原理。本文介绍的场景是从浏览器发起start请求,然后在服务中通过RestTemplate访问另一个服务end。代码如下:

@RestController
public class TestController {
    private static Logger log = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("start")
    public String start(){
        log.info("start收到请求");
        restTemplate.getForObject("http://localhost:8081/end",String.class);
        log.info("start请求处理结束");
        return "1";
    }
    @RequestMapping("end")
    public String end(){
        log.info("end收到请求");
        log.info("end请求处理结束");
        return "2";
    }
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

下面按照该场景介绍一下sleuth如何执行的。

三、原理解析

1、spring.factories文件

spring boot启动时,需要执行自动配置类。自动配置类都在sleuth-core.jar包的spring.factories文件中。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
# 下面三个自动配置类在任何场景下都需要执行,它们是基础类
org.springframework.cloud.sleuth.annotation.SleuthAnnotationAutoConfiguration,\
org.springframework.cloud.sleuth.autoconfig.TraceAutoConfiguration,\
org.springframework.cloud.sleuth.propagation.SleuthTagPropagationAutoConfiguration,\
#下面每个自动配置类是应用于具体框架或者中间件的,比如
#TraceWebClientAutoConfiguration:对RestTemplate、WebClient等创建拦截器,当发出请求时可以对其拦截在请求的header中添加链路信息
org.springframework.cloud.sleuth.instrument.web.TraceHttpAutoConfiguration,\
org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration,\
org.springframework.cloud.sleuth.instrument.web.client.TraceWebClientAutoConfiguration,\
org.springframework.cloud.sleuth.instrument.web.client.TraceWebAsyncClientAutoConfiguration,\
org.springframework.cloud.sleuth.instrument.async.AsyncAutoConfiguration,\
org.springframework.cloud.sleuth.instrument.async.AsyncCustomAutoConfiguration,\
org.springf
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值