15. 集成
15.1. OpenTracing
Spring Cloud Sleuth 与 OpenTracing 兼容。
如果类路径上有 OpenTracing,我们会自动注册 OpenTracing Tracer Bean。
如果你想禁用它,请将 spring.sleuth.opentracing.enabled 设置为 false
<h3>15.2. 可运行和可调用接口</h3>
如果你将逻辑包装在 Runnable 或 Callable 中,你可以将这些类包装在其 Sleuth 代表类中,如下例所示 for Runnable:
Runnable runnable = new Runnable() {
@Override
public void run() {
// do some work
}
@Override
public String toString() {
return "spanNameFromToStringMethod";
}
};
// Manual `TraceRunnable` creation with explicit "calculateTax" Span name
Runnable traceRunnable = new TraceRunnable(this.tracing, spanNamer, runnable,
"calculateTax");
// Wrapping `Runnable` with `Tracing`. That way the current span will be available
// in the thread of `Runnable`
Runnable traceRunnableFromTracer = this.tracing.currentTraceContext()
.wrap(runnable);
下面的示例展示了如何执行此操作,对于Callable:
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
return someLogic();
}
@Override
public String toString() {
return "spanNameFromToStringMethod";
}
};
// Manual `TraceCallable` creation with explicit "calculateTax" Span name
Callable<String> traceCallable = new TraceCallable<>(this.tracing, spanNamer,
callable, "calculateTax");
// Wrapping `Callable` with `Tracing`. That way the current span will be available
// in the thread of `Callable`
Callable<String> traceCallableFromTracer = this.tracing.currentTraceContext()
.wrap(callable);
这样,您就确保为每次执行创建和关闭一个新的跨度。
15.3. 断路器
If you have Spring Cloud CircuitBreaker on the classpath, we will wrap the passed command Supplier and the fallback Function in its trace representations. 为了禁用此 instrumentation,请将 spring.sleuth.circuitbreaker.enabled 设置为 false。
15.4. Hystrix
15.4.1. 自定义并发策略
我们将一个名为 HystrixConcurrencyStrategy 的自定义 2 注册为 TraceCallable,它用它们的 Sleuth 代表包装所有 Callable 实例。该策略根据在 Hystrix 命令被调用之前是否已经开始跟踪,要么开始或继续跨度。可选地,您可以将 spring.sleuth.hystrix.strategy.passthrough 设置为 true,以便仅将跟踪上下文传播到 Hystrix 执行线程,如果您不想启动新跨度。要禁用自定义 Hystrix 并发性策略,请将 spring.sleuth.hystrix.strategy.enabled 设置为 false。
15.4.2. 手动命令设置
假设你有以下HystrixCommand:
HystrixCommand<String> hystrixCommand = new HystrixCommand<String>(setter) {
@Override
protected String run() throws Exception {
return someLogic();
}
};
为传递追踪信息,必须将相同的逻辑包装在 Sleuth 版本的 HystrixCommand 中,即调用 TraceCommand,如下例所示:
TraceCommand<String> traceCommand = new TraceCommand<String>(tracer, setter) {
@Override
public String doRun() throws Exception {
return someLogic();
}
};
15.5. RxJava
We register a custom RxJavaSchedulersHook that wraps all Action0 instances in their Sleuth representative, which is called TraceAction. The hook either starts or continues a span, depending on whether tracing was already going on before the Action was scheduled. To disable the custom RxJavaSchedulersHook, set the spring.sleuth.rxjava.schedulers.hook.enabled to false.
你可以为线程名称定义一个列表,对于这些名称,您不想创建跨度。要实现这一点,请在spring.sleuth.rxjava.schedulers.ignoredthreads属性中提供由逗号分隔的正则表达式列表。
| 建议使用Reactor支持进行响应式编程和Sleuth。 |
15.6. HTTP 集成
本部分中的某些功能可以通过将属性设置为值等于 false 的 spring.sleuth.web.enabled 来禁用。
15.6.1. 过滤器
通过TracingFilter,对所有采样的传入请求都会创建一个。
这个的名称是http:加上发送请求的路径。
例如,如果请求被发送到/this/that,那么名称将是http:/this/that。
您可以通过设置spring.sleuth.web.skipPattern属性来配置您想要跳过的哪些 URI。
如果您在类路径上有ManagementServerProperties,则其值contextPath会追加到提供的跳过模式。
如果您希望重用 Sleuth 的默认跳过模式,并仅追加自己的内容,请使用 7。
默认情况下,所有 Spring Boot actuator 端点都会自动添加到跳过模式中。
如果你想要禁用这种行为,请将 spring.sleuth.web.ignore-auto-configured-skip-patterns
设置为 true。
要更改跟踪过滤器注册顺序,请设置spring.sleuth.web.filter-order属性。
要禁用记录未捕获异常的筛选器,您可以禁用
spring.sleuth.web.exception-throwing-filter-enabled属性。
15.6.2. 处理程序拦截器
因为我们要使跨度名称更加精确,所以使用一个TraceHandlerInterceptor,它可以包裹一个现有的HandlerInterceptor,也可以直接添加到已有的HandlerInterceptors列表中。
TraceHandlerInterceptor为给定HttpServletRequest添加一个特殊的请求属性。
如果TracingFilter看不到此属性,它将创建一个“fallback”跨度,这是一个服务器端创建的额外跨度,以便在UI中正确显示跟踪。
如发生这种情况,可能缺少仪表化。
在这种情况下,请在Spring Cloud Sleuth中提交问题。
15.6.3. 异步 Servlet 支持
如果控制器返回Callable或WebAsyncTask,Spring Cloud Sleuth将继续使用现有的跨度而不是创建新跨度。
15.6.4。支持WebFlux
通过TraceWebFilter,所有采样的传入请求都会导致创建一个Span。
该Span的名称是http:+要发送请求的路径。
例如,如果请求被发送到/this/that,那么名称是http:/this/that。
您可以使用spring.sleuth.web.skipPattern属性配置您希望跳过的哪些URI。
如果您在类路径上有ManagementServerProperties,它的值contextPath会追加到提供的跳过模式。
如果您想重用Sleuth的默认跳过模式并附加您自己的,可以通过使用spring.sleuth.web.additionalSkipPattern传递这些模式。
要更改跟踪过滤器注册顺序,请设置spring.sleuth.web.filter-order属性。
15.6.5. Dubbo组件领场支持
通过与 Brave 的集成,Spring Cloud Sleuth 支持 Dubbo。只需要添加 brave-instrumentation-dubbo 依赖项:
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-instrumentation-dubbo</artifactId>
</dependency>
还需要设置一个dubbo.properties文件,其内容如下所示:
dubbo.provider.filter=tracing
dubbo.consumer.filter=tracing
15.7. HTTP 客户端集成
15.7.1. 同步 Rest Template
我们注入一个RestTemplate拦截器,以确保所有跟踪信息都能传递到请求中。
每次调用都会创建一个新的Span。
在接收到响应时,该Span会被关闭。
要阻止同步RestTemplate功能,请将spring.sleuth.web.client.enabled设置为false。
您必须将RestTemplate注册为bean,以便注入拦截器。如果您使用new关键字创建RestTemplate实例,则仪器仪表不工作。 |
15.7.2。异步 Rest Template
Starting with Sleuth 2.0.0, we no longer register a bean of AsyncRestTemplate type.
It is up to you to create such a bean.
Then we instrument it. |
阻止功能 AsyncRestTemplate,将 spring.sleuth.web.async.client.enabled 设置为 false。 要禁用默认创建 TraceAsyncClientHttpRequestFactoryWrapper,请设置 spring.sleuth.web.async.client.factory.enabled 到 false。 如果不想完全创建 AsyncRestClient,请设置 spring.sleuth.web.async.client.template.enabled 为 false。
<span>多个异步Rest模板</span>
有时候你需要使用异步 Rest 模板的多个实现。 在下面的代码片段中,您可以看到如何设置这样的自定义 0。:
@Configuration
@EnableAutoConfiguration
static class Config {
@Bean(name = "customAsyncRestTemplate")
public AsyncRestTemplate traceAsyncRestTemplate() {
return new AsyncRestTemplate(asyncClientFactory(),
clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
ClientHttpRequestFactory clientHttpRequestFactory = new CustomClientHttpRequestFactory();
// CUSTOMIZE HERE
return clientHttpRequestFactory;
}
private AsyncClientHttpRequestFactory asyncClientFactory() {
AsyncClientHttpRequestFactory factory = new CustomAsyncClientHttpRequestFactory();
// CUSTOMIZE HERE
return factory;
}
}
15.7.3. WebClient
我们注入了一个ExchangeFilterFunction实现,它创建一个跨度,并通过成功和错误回调来处理关闭客户端跨度。
阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 false。
您必须注册一个WebClient或WebClient.Builder,以便应用跟踪 instrumentation。如果您手动创建一个WebClient或WebClient.Builder,则 instrumentation 不起作用。 |
15.7.4. 驾驶员游览器
如果您使用Traverson库,可以将RestTemplate注入到Traverson对象中作为bean。因为RestTemplate已经被截获了,所以您的客户端也获得了完整的跟踪支持。下面的伪代码展示了如何做到这一点:
@Autowired RestTemplate restTemplate;
Traverson traverson = new Traverson(URI.create("https://some/address"),
MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8).setRestOperations(restTemplate);
// use Traverson
15.7.5. Apache HttpClientBuilder 和 HttpAsyncClientBuilder
我们对HttpClientBuilder和HttpAsyncClientBuilder进行仪器采集,这样跟踪上下文就会注入到发送的请求中。
阻止这些功能,请将 spring.sleuth.web.client.enabled 设置为 false。
15.7.6 Netty HttpClient
我们对 Netty 的 HttpClient 进行监控。
阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 false。
您必须将 0 作为 bean 进行注册,以便进行仪器化。如果您使用 2 关键字创建 1 实例,则不会执行仪器化。 |
15.7.7. UserInfoRestTemplateCustomizer
我们对 Spring Security 的 UserInfoRestTemplateCustomizer 进行监控。
阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 false。
15.8. Feign
默认情况下,Spring Cloud Sleuth 通过 TraceFeignClientAutoConfiguration 集成 Feign。
可以通过将 spring.sleuth.feign.enabled 设置为 false 来完全禁用它。
如果这样设置,就不会进行任何与 Feign 相关的仪器化。
部分Feign仪器是由FeignBeanPostProcessor完成的。您可以将其设置为spring.sleuth.feign.processor.enabled以禁用它。如果您将其设置为false,则Spring Cloud Sleuth不会对任何自定义Feign组件进行仪器。但是,所有默认仪器仍然存在。
15.9. gRPC
Sprin Cloud Sleuth通过TraceGrpcAutoConfiguration为gRPC提供工具支持。你可以通过将spring.sleuth.grpc.enabled设置为false来完全禁用它。
15.9.1. 变体1
依赖项
| Spring框架的gRPC集成依赖于两个外部库来对客户端和服务端进行仪器检测,为了启用仪器检测,这两个外部库都必须在类路径上。 |
Maven:
<dependency>
<groupId>io.github.lognet</groupId>
<artifactId>grpc-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-instrumentation-grpc</artifactId>
</dependency>
Gradle:
compile("io.github.lognet:grpc-spring-boot-starter")
compile("io.zipkin.brave:brave-instrumentation-grpc")
服务器仪器仪表
Spring Cloud Sleuth 利用 grpc-spring-boot-starter 将 Brave 的 gRPC 服务拦截器与所有使用 @GRpcService 注解的服务进行注册。
客户端仪器
gRPC 客户端利用一个ManagedChannelBuilder来构建用于与 gRPC 服务器通信的ManagedChannel。原生ManagedChannelBuilder提供了静态方法作为构造ManagedChannel实例的入口点,但是这种机制不受 Spring 应用上下文的影响。
SprSpringAwareManagedChannelBuilder提供了一个可以自定义的组件,该组件可以通过 Spring 应用上下文进行配置,并由 gRPC 客户端注入。 在创建 ManagedChannel 实例时必须使用此构建器。 |
跟踪器创建一个TracingManagedChannelBuilderCustomizer,并将Brave的客户端拦截器注入到SpringAwareManagedChannelBuilder中。
15.9.2. 变体 2
Grpc Spring Boot Starter 自动检测 Spring Cloud Sleuth 和 brave 的 gRPC 检测,并注册必要的客户端和/或服务器工具。
15.10. 异步通信
15.10.1. @Async 注解方法
在 Spring Cloud Sleuth 中,我们为异步相关的组件进行仪器化,以便跟踪信息可以在线程之间传递。您可以将值设置为 0,以禁用此行为。如果要启用此功能,请将值设置为 1。
如果用@Async注释您的方法,我们将自动按如下方式修改现有的Span:
-
如果该方法使用了
@SpanName注释,注释的值就是跨度的名称。 -
如果方法未用
@SpanName注释,跨度名称就是注释方法的名称。 -
span 元素带有方法的类名和方法名。
如果要保留原始名称(例如由接收 HTTP 请求创建的跨度)
您应该用@NewSpan注释包装带有@Async注释的方法,或者手动创建新的跨度。
15.10.2. @Scheduled 注解方法
在Spring Cloud Sleuth中,我们对定时任务方法执行进行仪器化,以便在不同线程间传递追踪信息。
你可以通过将spring.sleuth.scheduled.enabled设置为false来禁用这种行为。
如果使用@Scheduled注解方法,我们会自动生成一个新的跨度,具有以下特征:
-
span 名称是注释方法名。
-
span 元素带有方法的类名和方法名。
如果您希望跳过某些使用@Scheduled注解的类的span创建,可以设置spring.sleuth.scheduled.skipPattern,并提供一个与@Scheduled注解类完全限定名匹配的正则表达式。如果同时使用spring-cloud-sleuth-stream和spring-cloud-netflix-hystrix-stream,每个Hystrix指标都会生成一个span,并发送到Zipkin。这种行为可能会令人困扰。因此,默认情况下,spring.sleuth.scheduled.skipPattern=org.springframework.cloud.netflix.hystrix.stream.HystrixStreamTask。
15.10.3. 执行器、ExecutorService 和 ScheduledExecutorService
我们提供LazyTraceExecutor、TraceableExecutorService和TraceableScheduledExecutorService。这些实现每次提交、调用或安排新任务时都会创建跨度。
这下分空签似在发现,TraceableExecutorService 可以在CompletableFuture 参数时传递进一些时长,
CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> {
// perform some logic
return 1_000_000L;
}, new TraceableExecutorService(beanFactory, executorService,
// 'calculateTax' explicitly names the span - this param is optional
"calculateTax"));
Sleuth 无法与 parallelStream() 一起开箱即用。
如果你想要通过流传播跟踪信息,就必须使用 supplyAsync(...) 的方法,如前面所示。 |
如果您希望排除某些实现Executor接口的bean以创建跨度,请使用spring.sleuth.async.ignored-beans属性,并提供一个bean名称列表。
执行器的定制
Sometimes, you need to set up a custom instance of the AsyncExecutor. The following example shows how to set up such a custom Executor:
@Configuration
@EnableAutoConfiguration
@EnableAsync
// add the infrastructure role to ensure that the bean gets auto-proxied
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static class CustomExecutorConfig extends AsyncConfigurerSupport {
@Autowired
BeanFactory beanFactory;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// CUSTOMIZE HERE
executor.setCorePoolSize(7);
executor.setMaxPoolSize(42);
executor.setQueueCapacity(11);
executor.setThreadNamePrefix("MyExecutor-");
// DON'T FORGET TO INITIALIZE
executor.initialize();
return new LazyTraceExecutor(this.beanFactory, executor);
}
}
为了确保您的配置能够得到后期处理,请记住在您的@Role(BeanDefinition.ROLE_INFRASTRUCTURE)类上添加@Configuration |
15.11. 消息处理
本部分中的某些功能可以通过将属性设置为值等于 false 的 spring.sleuth.messaging.enabled 来禁用。
15.11.1. Spring集成与Spring云流
Spring Cloud Sleuth与Spring Integration\集成。它为发布和订阅事件创建跨度。要禁用Spring Integration instrumentation,请将spring.sleuth.integration.enabled设置为2\。
你可以提供spring.sleuth.integration.patterns模式,显式地指定要包含进行跟踪的通道名称。默认情况下,除了hystrixStreamOutput通道外,所有通道都包含在内。
当使用 Executor 来构建一个 Spring 集成 IntegrationFlow 时,必须使用 Executor 的无跟踪版本。
在 TraceableExecutorService 上装饰 Spring 集成 Executor Channel 会导致 spans 不正确地关闭。 |
如果您想自定义从消息头中读取和写入跟踪上下文的方式,只需注册相应类型的bean即可:
-
Propagation.Setter<MessageHeaderAccessor, String>- for writing headers to the message -
Propagation.Getter<MessageHeaderAccessor, String>- 指从消息中读取头信息
15.11.2. Spring RabbitMq
我们对RabbitTemplate进行插桩,以便将跟踪头注入到消息中。
阻止此功能,请将 spring.sleuth.messaging.rabbit.enabled 设置为 false。
15.11.3. Spring Kafka
我们对 Spring Kafka 的 ProducerFactory 和 ConsumerFactory 进行仪器
te,以便跟踪头文件被注入到创建的 Spring Kafka 的 Producer 和 Consumer 中。
阻止此功能,请将 spring.sleuth.messaging.kafka.enabled 设置为 false。
15.11.4. Spring Kafka Streams
我们对 KafkaStreams KafkaClientSupplier 进行了增强,以便在 Producer 和 Consumer`s. A `KafkaStreamsTracing bean 中注入跟踪头
允许通过额外的 TransformerSupplier 和 ProcessorSupplier 方法进行进一步的增强。
阻止此功能,请将 spring.sleuth.messaging.kafka.streams.enabled 设置为 false。
15.11.5. Spring JMS
我们对JmsTemplate进行监控,以便将跟踪标头注入到消息中。我们也支持在消费者端使用@JmsListener注解的方法。
阻止此功能,请将 spring.sleuth.messaging.jms.enabled 设置为 false。
| 我们不支持 JMS 的 baggage propagation |
15.11.6. Spring Cloud AWS 消息传递 SQS
我们对@SqsListener进行插桩,它由org.springframework.cloud:spring-cloud-aws-messaging提供,以便从消息中提取跟踪头并将跟踪放入上下文中。
阻止此功能,请将 spring.sleuth.messaging.sqs.enabled 设置为 false。
15.12. Zuul
我们通过使用跟踪信息来丰富Ribbon请求,从而对Zuul Ribbon集成进行增强。要禁用Zuul支持,请将spring.sleuth.zuul.enabled属性设置为false。
15.13. Redis
我们将 tracing 属性设置为 Lettcue ClientResources 实例,以启用内置的 Brave 跟踪功能。
要禁用 Redis 支持,请将 spring.sleuth.redis.enabled 属性设置为 false。
15.14. Quartz
我们通过向Quartz调度器添加作业/触发器监听器来监控quartz作业。
要关闭此功能,请将spring.sleuth.quartz.enabled属性设置为false。
15.15. Reactor项目
15.15.1. Spring Cloud Sleuth 2.2.8(含)起
从新的 Reactor 队列包装机制(Reactor 3.3.14)开始,我们正在改进 Reactor 切换线程的方式。您应该会观察到性能有显著提升。为了启用此功能,必须将 spring.sleuth.reactor.decorate-queues 设置为 true。
15.15.2. 升级到 Spring Cloud Sleuth 2.2.8(不包括)
对于依赖 Project Reactor 的项目(例如 Spring Cloud Gateway),我们建议将 spring.sleuth.reactor.decorate-on-each 选项改为 false。这样相比标准的仪器化机制,应该能观察到更高的性能提升。这个选项的作用是用 onLast 操作符包装而不是 onEach,这将导致创建更少的对象。缺点是当 Project Reactor 切换线程时,跟踪传播将继续正常进行,但任何依赖于 ThreadLocal 的内容(例如 MDC 条目)可能会出现错误。