sleuth
链路追踪, 可以结合 zipkin, 将信息发送到 zipkin, 通过 zipkin 来存储信息, 通过 zipkin ui 来展示数据
耗时分析
通过 Sleuth 可以很方便的了解到每个采样请求的耗时,从而分析出哪些服务调用比较耗时
可视化错误
对于程序未捕捉的异常,可以通过集成 Zipkin 服务界面上看到
brave
捕捉分布式系统之间调用信息的工具库,然后将这些信息以 span 的形式发给 Zipkin
Zipkin
一个分布式跟踪系统, 收集微服务架构中延迟时间数据,和 Sleuth 结合可以提供可视化 Web 界面分析调用链路耗时情况
java -jar zipkin-server-2.12.2-exec.jar
org.springframework.cloud/spring-cloud-starter-zipkin
当 spring-cloud-sleuth-zipkin 包含在 classpath 中时,应用程序将生成并收集与 zipkin 兼容的追踪记录。默认情况下,会通过 HTTP 将它们发送到本地主机(端口9411)上的 Zipkin 服务器
# spring.zipkin.locator.discovery.enabled=true
spring.zipkin.baseurl=http://localhost:9411/
# 导出 Span 的概率(默认值:0.1,即10%)
spring.sleuth.sampler.probability=1.0
sleuth 对 feign 的支持
sleuth 通过 TracingFeignClient 实现了 feign.client 接口, 在执行 http 调用前, 在 header 中添加 Span 信息
sleuth 对 RestTemplate 的支持
需要将 RestTemplate 注册为一个bean, 这样 sleuth 定义的拦截器才能注入进来, RestTemplate 在执行 execute 的时候, Request 会经过拦截器的处理, 添加上 span 信息
sleuth 对多线程的支持
sleuth 提供了 LazyTraceExecutor, traceableExecutorService, traceableScheduledExecutorService 多线程实现
服务端通过 Filter 接收客户端 span 信息
服务端的 sleuth 通过 brave 的 TracingFilter 获取 span 信息,可以编写一个 filter 来获取或增加修改 span 信息
baggage
sleuth 提供了一个功能接口,可以让你的数据跟着 sleuth 一起往后接连传递,比如,登录信息的传递
session id 的传递
org.springframework.cloud/spring-cloud-starter-sleuth
服务消费方
1.编写 filter
/**
* 自定义过滤器,
* 获取当前的 SessionId, 放入 Baggage 中
* 注意, 因为不是所有的请求都需要往后传递, 所以会对一些请求跳过执行
*/
@Component
@Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER + 1)
public class SessionFilter extends GenericFilterBean {
private Pattern skipPattern = Pattern.compile(SleuthWebProperties.DEFAULT_SKIP_PATTERN);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
throw new ServletException("Filter just supports HTTP requests");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
boolean skip = skipPattern.matcher(httpRequest.getRequestURI()).matches();
if (!skip) {
// 将 SessionId 放到 Baggage 中
ExtraFieldPropagation.set("SessionId", httpRequest.getSession().getId());
}
filterChain.doFilter(request, response);
}
}
2.配置文件 bootstrap
# 注意, Sleuth2.0.0 之后, baggage 的 key 必须在这里配置才能生效
spring.sleuth.baggage-keys= - SessionId
服务提供方
java 中获取
ExtraFieldPropagation.get("SessionId")