技术标签: # SpringCloud
Sleuth 通过 traceId 实现了对分布式系统调用链路的跟踪。在一次服务请求链路中,会保持并传递一个 traceId,从而将不同服务的请求跟踪信息串联起来,不同服务的 traceId 相同表示处在同一请求链中。
基于 HTTP 请求的数据传递有两种方式:一种是做为参数传递,另一种是做为头信息传递。而 Sleuth 的 traceId 属于附加信息,不参与实际的业务,所以做为参数传递并不合适,实际也是作为头信息来传递的。
分布式系统中的服务调用链路跟踪在理论上并不复杂,主要有个关键点,一个是为请求链路创建唯一跟踪标识,二个统计各个处理单元的延迟时间。
参考 Spring Cloud系列(十三):分布式服务链路跟踪 Sleuth 中的示例项目,Sleuth 会在请求的 Header 中增加实现跟踪需的信息,给远程调用接口打上断点,使用 request.getHeaderNames() 取出所有头信息。
["x-b3-spanid","x-b3-parentspanid","x-b3-sampled","x-b3-traceid","accept","user-agent","host","connection"]
可以看到,在请求头信息中多了 4 个属性:
Sleuth 会把跟踪数据 (appname、traceId、spanId、exportable) 添加到 Slf4J MDC 中,因此您可以从日志聚合器中的给定跟踪或跨度中提取所有日志,如以下示例日志中所示:
2016-02-02 15:30:57.902 INFO [bar,6bfd228dc00d216b,6bfd228dc00d216b,false] 23030 --- [nio-8081-exec-3] ... 2016-02-02 15:30:58.372 ERROR [bar,6bfd228dc00d216b,6bfd228dc00d216b,false] 23030 --- [nio-8081-exec-3] ... 2016-02-02 15:31:01.936 INFO [bar,46ab0d418373cbc9,46ab0d418373cbc9,false] 23030 --- [nio-8081-exec-4] ...
MDC 的实现实际是将需要记录到日志的信息设置到当前线程的上下文(ThreadContext)中。
MDC 中的信息:[appname,traceId,spanId,exportable]
跟踪信息收集默认是 0.1(10%) 的采样比例,可通过 probability 属性修改;或可采用每秒速率来控制采集数据,属性是 rate。
# 跟踪信息收集采样比例,默认 0.1,为 1 是即 100%,收集所有 spring.sleuth.sampler.probability=1 # 每秒速率,即每秒最多能跟踪的请求,rate 优先 spring.sleuth.sampler.rate=50
源码分析基于Spring Cloud Hoxton,Spring Cloud Sleuth版本为2.2.0.RELEASE
SpringBoot 2开始使用了brave框架完成日志收集,brave是zipkin官方提供的java版本客户端,它将收集的跟踪信息,以Span的形式上报给Zipkin系统。
下面假设有client,server两个工程,调用链路如下:
用户 -> client --> server
我们来探讨以下几个问题
用户调用client时,client如何生成Span信息
client调用server时,如何将Span发送到server
server如何接收cliend的Span信息
client,server如何发送Span到zipkin
注意,本文是基于SpringMvc+RestTeamplate的请求调用的,而非WebFlux异步调用。
问题1和问题3,都由LazyTracingFilter处理,它在TraceWebServletAutoConfiguration中初始化。(本文部分源码来自于brave框架)LazyTracingFilter#doFilter -> (brave)TracingFilter#doFilter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
...
// #1
Span span = handler.handleReceive(new HttpServerRequest(httpRequest));
// #2
request.setAttribute(SpanCustomizer.class.getName(), span.customizer());
request.setAttribute(TraceContext.class.getName(), span.context());
Throwable error = null;
// #3
Scope scope = currentTraceContext.newScope(span.context());
try {
chain.doFilter(httpRequest, httpResponse);
} ...
finally {
// #4
scope.close();
if (servlet.isAsync(httpRequest)) { // we don't have the actual response, handle later
servlet.handleAsync(handler, httpRequest, httpResponse, span);
} else { // we have a synchronous response, so we can finish the span
handler.handleSend(servlet.httpServerResponse(httpRequest, httpResponse), error, span);
}
}
}
public Span handleReceive(HttpServerRequest request) {
// #1
Span span = nextSpan(defaultExtractor.extract(request), request);
// #2
return handleStart(new HttpServerRequest.ToHttpAdapter(request), request.unwrap(), span);
}
LazyTracingClientHttpRequestInterceptor负责实现该功能。它在TraceWebClientAutoConfiguration中构建。LazyTracingClientHttpRequestInterceptor#interceptor -> TracingClientHttpRequestInterceptor#intercept(brave)
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
// #1
Span span = handler.handleSend(new HttpClientRequest(request));
HttpClientResponse response = null;
Throwable error = null;
// #2
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
// #3
ClientHttpResponse result = execution.execute(request, body);
response = new HttpClientResponse(result);
return result;
} catch (IOException | RuntimeException | Error e) {
error = e;
throw e;
} finally {
// #4
handler.handleReceive(response, error, span);
}
}
public Span handleSend(HttpClientRequest request, Span span) {
...
// #1
defaultInjector.inject(span.context(), request);
// #2
return handleStart(new HttpClientRequest.ToHttpAdapter(request), request.unwrap(), span);
}
那么Spring如何将span发送到zipkin?先看一个brave框架上报Span的简单例子
Sender sender = URLConnectionSender.create("http://localhost:9411/api/v1/spans")
AsyncReporter asyncReporter = AsyncReporter.builder(sender)
.build(SpanBytesEncoder.JSON_V2);
Tracing tracing = Tracing.newBuilder()
.spanReporter(asyncReporter)
.build();
Tracer tracer = tracing.tracer();
Span span = tracer.newTrace().name("encode").start();
...
span.finish();
我们并不要自己上报数据,span.finish()
方法中,brave会帮我们完成上报Span工作。
看一下上例中brave的组件类
在Spring Cloud Sleuth中,
文章浏览阅读2.1k次。基于百度智能云平台的情感倾向计算_百度智能云算法原理在哪找
文章浏览阅读273次。LoRa无线模块作为近年来最火热的低功耗远距离的无线模块,在市场上是非常受欢迎的。合理规范安装使用是LoRa无线模块可以长期稳定工作的重要因素之一,同时也可以避免产生损坏,减少维护和项目运维成本。那么LoRa模块在使用安装过程中,要注意什么,下面就来简单介绍一下。_lora模块没有天线头能用吗
文章浏览阅读4.8k次,点赞2次,收藏6次。很有用但是不不知道怎么说,写个例子,总之方便多了,并且容易管理,重复利用强1、自定一个类,实现 javax.servlet.jsp.tagext.Tag;(PageTag.java)2、建立一个tld文件(myfTag.tld)3、建立一个freemaker文件*.ftl(page.ftl)4、建立jsp页面,导入标签(%@taglib prefix="myf" uri="/m_public class goodsgallytag extends basefreemarkertag这是什么写法
文章浏览阅读6次。所需工具 : cmake for windows 和 git for windows原理:protobuf 是google的一个开源项目,其源代码在github上可以下载到,并且源码都采用cmake来构建,所以我们可以把源码下载到本地,然后了利用cmake构建本地工程,然后编译.步骤一:下载源码 复制以下代码,保存到download_protobuf_source.bat 文件中...
文章浏览阅读1.6k次,点赞2次,收藏13次。系列文章目录(一)ILRuntime基础使用(二)Addressable基础使用目录系列文章目录简介流程DLL 转换代码DLL 加载代码简介把热更项目的 DLL 作为 addressable 的资源来实现热更新流程资源部分(1)addressable 是不支持 dll 的,所以需要把 dll 文件加工成 addressable 支持的格式(2)直接 File.ReadAllBytes 读取成 bytes 然后 File.WriteAllBytes 保存(3)保存文件的后缀为 .b_unity dll 和 addresable 一起使用
文章浏览阅读154次。g2o optimizeAre you looking to add Google Optimize on your WordPress site? 您是否要在WordPress网站上添加Google Optimize? Google Optimize is a free tool by Google that helps website owners optimize their site..._google optimize
文章浏览阅读3.1k次。Linux备份系统镜像并对镜像中LVM分区文件的修改_dd 备份lvm
文章浏览阅读201次。 tcpdump是一个网络抓包工具,用于捕获和分析网络数据包。它可以在 Unix/Linux 系统上通过命令行进行使用。tcpdump能够截获网络传输过程中的数据包,并将这些数据包的内容以及相关的信息显示出来,方便网络管理员和分析师进行网络故障排查、网络性能分析、网络安全监控等任务。_tcpdump使用方法
文章浏览阅读2.3k次。说明:本文中使用的例子均在下面的数据库表tt2下执行:一、concat()函数1、功能:将多个字符串连接成一个字符串。2、语法:concat(str1, str2,...)返回结果为连接参数产生的字符串,如果有任何一个参数为null,则返回值为null。3、举例:例1:select concat (id, name, score) as info from tt2;中间有一行为null是因为tt2..._mysql concat将查询到的list拼接
文章浏览阅读1.1w次,点赞2次,收藏20次。1.修改router中index.js文件中每个路由加上meta:{ title: ‘首页’}const router = new Router({ mode: '', routes: [ { path: '/', name: '', component: , meta:{ // title: '首页'
文章浏览阅读129次。文章目录一、Ribbon是什么?二、使用步骤1.消费者2.提供者2.启动测试总结一、Ribbon是什么?再说Ribbon之前,先来谈谈什么是负载均衡**,负载均衡简单来说就是将用户的请求平摊到多个服务器上,从而达到系统的高可用(Hign Availability)**LB简单分为两类,第一类是集中式LB(LoadBalance),第二类是进程式LB(LoadBalance)集中式的话,意思是在服务的提供方和消费方之间使用独立的LB设备,nginx就是这样子的,当请求来到nginx的时候,nginx通过_yam设置ribbon
文章浏览阅读183次。1344 走格子题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1344题目有编号1-n的n个格子,机器人从1号格子顺序向后走,一直走到n号格子,并需要从n号格子走出去。机器人有一个初始能量,每个格子对应一个整数A[i],表示这个格子的能量值。如果A[i] > 0,机器人走到这个格子能够获取A[i]_走格子 51nod - 1344 题解