Spring Cloud Sleuth 集成

1. 异步通信

在本节中,我们将介绍如何使用Spring Cloud Sleuth来自定义异步通信。spring-doc.cadn.net.cn

1.1. @Async Annotated methods

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

在 Spring Cloud Sleuth 中,我们为异步相关的组件进行仪器化,以便跟踪信息可以在线程之间传递。您可以将值设置为 0,以禁用此行为。如果要启用此功能,请将值设置为 1。spring-doc.cadn.net.cn

如果用@Async注释您的方法,我们将自动按如下方式修改现有的Span:spring-doc.cadn.net.cn

如果要保留原始名称(例如由接收 HTTP 请求创建的跨度) 您应该用@NewSpan注释包装带有@Async注释的方法,或者手动创建新的跨度。spring-doc.cadn.net.cn

1.2. @Scheduled 被注解的方法

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

在Spring Cloud Sleuth中,我们对定时任务方法执行进行仪器化,以便在不同线程间传递追踪信息。 你可以通过将spring.sleuth.scheduled.enabled设置为false来禁用这种行为。spring-doc.cadn.net.cn

如果使用@Scheduled注解方法,我们会自动生成一个新的跨度,具有以下特征:spring-doc.cadn.net.cn

如果想跳过某些@Scheduled注解类的span创建,可以设置spring.sleuth.scheduled.skipPattern,并指定一个正则表达式来匹配@Scheduled注解类的全限定名。spring-doc.cadn.net.cn

1.3. 执行器,执行器服务和计划执行器服务

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们提供 LazyTraceExecutorTraceableExecutorServiceTraceableScheduledExecutorService。 这些实现会在每次提交、调用或调度新任务时创建 span。spring-doc.cadn.net.cn

这下分空签似在发现,TraceableExecutorService 可以在CompletableFuture 参数时传递进一些时长,
spring-doc.cadn.net.cn

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(…​) 的方法,如前面所示。

如果要排除从跨度创建中,可以使用 1 属性,在其中可以提供一组 bean 名称。您可以使用 0 接口实现的 bean。spring-doc.cadn.net.cn

您可以通过将spring.sleuth.async.enabled值设置为false来禁用此行为。spring-doc.cadn.net.cn

<h3>1.3.1. 自定义执行程序</h3>

Sometimes, you need to set up a custom instance of the AsyncExecutor. The following example shows how to set up such a custom Executor:spring-doc.cadn.net.cn

@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@EnableAsync
// add the infrastructure role to ensure that the bean gets auto-proxied
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public 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),以便进行后处理。

2. HTTP 客户端集成

本部分中的某些功能可以通过将属性设置为值等于 falsespring.sleuth.web.client.enabled 来禁用。spring-doc.cadn.net.cn

2.1. 同步 Rest Template

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们注入一个RestTemplate拦截器,以确保所有跟踪信息都能传递到请求中。 每次调用都会创建一个新的Span。 在接收到响应时,该Span会被关闭。 要阻止同步RestTemplate功能,请将spring.sleuth.web.client.enabled设置为falsespring-doc.cadn.net.cn

您必须将RestTemplate注册为bean,以便注入拦截器。如果您使用new关键字创建RestTemplate实例,则仪器仪表不工作。

2.2. 异步 Rest 模板

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

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.enabledfalse。 如果不想完全创建 AsyncRestClient,请设置 spring.sleuth.web.async.client.template.enabledfalsespring-doc.cadn.net.cn

2.2.1多个异步Rest模板

有时候你需要使用异步 Rest 模板的多个实现。 在下面的代码片段中,您可以看到如何设置这样的自定义 0。:spring-doc.cadn.net.cn

@Configuration(proxyBeanMethods = false)
public static class TestConfig {

    @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;
    }

}

2.2.2. WebClient

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们注入了一个ExchangeFilterFunction实现,它创建一个跨度,并通过成功和错误回调来处理关闭客户端跨度。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 falsespring-doc.cadn.net.cn

您必须将 WebClient 注册为一个 bean,以便应用跟踪检测功能。 如果使用 new 关键字创建了一个 WebClient 实例,则该检测功能将无法工作。

2.2.3. 驾驶员

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

如果您使用 Traver son 库,您可以将 1 作为 bean 注入到您的 Traver son 对象中。因为 2 已经进行了拦截,因此可以在您的客户端中获得完整的跟踪支持。以下伪代码显示了如何执行此操作:spring-doc.cadn.net.cn

@Autowired RestTemplate restTemplate;

Traverson traverson = new Traverson(URI.create("https://some/address"),
    MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON_UTF8).setRestOperations(restTemplate);
// use Traverson

2.2.4. Apache HttpClientBuilderHttpAsyncClientBuilder

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们对HttpClientBuilderHttpAsyncClientBuilder进行仪器化,以便将跟踪上下文注入到发送的请求中。spring-doc.cadn.net.cn

阻止这些功能,请将 spring.sleuth.web.client.enabled 设置为 falsespring-doc.cadn.net.cn

2.2.5. Netty HttpClient

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们对 Netty 的 HttpClient 进行监控。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 falsespring-doc.cadn.net.cn

您必须将 0 作为 bean 进行注册,以便进行仪器化。如果您使用 2 关键字创建 1 实例,则不会执行仪器化。

2.2.6. UserInfoRestTemplateCustomizer

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们对 Spring Security 的 UserInfoRestTemplateCustomizer 进行监控。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.web.client.enabled 设置为 falsespring-doc.cadn.net.cn

3. HTTP 服务器集成

本部分中的某些功能可以通过将属性设置为值等于 falsespring.sleuth.web.enabled 来禁用。spring-doc.cadn.net.cn

3.1. HTTP 过滤器

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

通过0 ,所有采样的传入请求都会导致创建一个跨度。您可以设置1 属性,以配置要跳过的哪些 URI。 如果类路径上有2 ,则其值3 会附加到提供的跳过模式。 如果您想重用Sleuth的默认跳过模式,并只是追加自己的,可以使用4 传递这些模式。 spring-doc.cadn.net.cn

默认情况下,所有 Spring Boot actuator 端点都会自动添加到跳过模式中。 如果你想要禁用这种行为,请将 spring.sleuth.web.ignore-auto-configured-skip-patterns 设置为 truespring-doc.cadn.net.cn

要更改跟踪过滤器注册顺序,请设置spring.sleuth.web.filter-order属性。spring-doc.cadn.net.cn

要禁用记录未捕获异常的筛选器,您可以禁用 spring.sleuth.web.exception-throwing-filter-enabled属性。spring-doc.cadn.net.cn

3.2. 处理程序拦截器

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

由于我们希望span名称更加精确,因此我们将TraceHandlerInterceptor用作包裹现有HandlerInterceptor或直接添加到现有HandlerInterceptors列表中的包装器。
TraceHandlerInterceptor为给定HttpServletRequest添加一个特殊的请求属性。
如果TracingFilter看不到此属性,则创建“回退”span,即在服务器端创建的additional span,以便在UI中正确显示trace。
如果发生这种情况,则可能缺少仪器。
在这种情况下,请在Spring Cloud Sleuth中提交issue。
spring-doc.cadn.net.cn

3.3. 异步Servlet支持

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

如果控制器返回CallableWebAsyncTask,Spring Cloud Sleuth将继续使用现有的跨度而不是创建新跨度。spring-doc.cadn.net.cn

3.4. WebFlux 支持

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

通过TraceWebFilter,所有采样的传入请求都会导致创建一个Span。 该Span的名称是http:+要发送请求的路径。 例如,如果请求被发送到/this/that,那么名称是http:/this/that。 您可以使用spring.sleuth.web.skipPattern属性配置您希望跳过的哪些URI。 如果您在类路径上有ManagementServerProperties,它的值contextPath会追加到提供的跳过模式。 如果您想重用Sleuth的默认跳过模式并附加您自己的,可以通过使用spring.sleuth.web.additionalSkipPattern传递这些模式。spring-doc.cadn.net.cn

为了在性能和上下文传播方面达到最佳效果,我们建议将 spring.sleuth.reactor.instrumentation-type 更改为 MANUAL。 要使用范围内的跨度执行代码,可以调用 WebFluxSleuthOperators.withSpanInScope。 示例:spring-doc.cadn.net.cn

@GetMapping("/simpleManual")
public Mono<String> simpleManual() {
    return Mono.just("hello").map(String::toUpperCase).doOnEach(WebFluxSleuthOperators
            .withSpanInScope(SignalType.ON_NEXT, signal -> log.info("Hello from simple [{}]", signal.get())));
}

要更改跟踪过滤器注册顺序,请设置spring.sleuth.web.filter-order属性。spring-doc.cadn.net.cn

4. 消息传递

本部分中的某些功能可以通过将属性设置为值等于 falsespring.sleuth.messaging.enabled 来禁用。spring-doc.cadn.net.cn

4.1. Spring 集成测试

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

Spring Cloud Sleuth与Spring Integration\集成。它为发布和订阅事件创建跨度。要禁用Spring Integration instrumentation,请将spring.sleuth.integration.enabled设置为2\。spring-doc.cadn.net.cn

你可以提供spring.sleuth.integration.patterns模式,显式地指定要包含进行跟踪的通道名称。默认情况下,除了hystrixStreamOutput通道外,所有通道都包含在内。spring-doc.cadn.net.cn

当使用 Executor 来构建一个 Spring 集成 IntegrationFlow 时,必须使用 Executor 的无跟踪版本。 在 TraceableExecutorService 上装饰 Spring 集成 Executor Channel 会导致 spans 不正确地关闭。

如果您想要自定义读取和写入消息头中的跟踪上下文的方式,只需要注册类型的 bean 即可:spring-doc.cadn.net.cn

4.1.2。自定义消息跨度

为了更改默认的span名称和标签,只需注册一个类型为MessageSpanCustomizer的bean。您也可以 覆盖现有的DefaultMessageSpanCustomizer以扩展现有的行为。spring-doc.cadn.net.cn

@Component
  class MyMessageSpanCustomizer extends DefaultMessageSpanCustomizer {
      @Override
      public Span customizeHandle(Span spanCustomizer,
              Message<?> message, MessageChannel messageChannel) {
          return super.customizeHandle(spanCustomizer, message, messageChannel)
                  .name("changedHandle")
                  .tag("handleKey", "handleValue")
                  .tag("channelName", channelName(messageChannel));
      }

      @Override
      public Span.Builder customizeSend(Span.Builder builder,
              Message<?> message, MessageChannel messageChannel) {
          return super.customizeSend(builder, message, messageChannel)
                  .name("changedSend")
                  .tag("sendKey", "sendValue")
                  .tag("channelName", channelName(messageChannel));
      }
  }

4.2. Spring Cloud Function 与 Spring Cloud Stream

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

Spring Cloud Sleuth 可以对 Spring Cloud Function 进行仪器。实现方式是提供一个参数为 3 的 0 或 1 或 2,例如 4。如果类型不是 5,则不会执行仪器。开箱即用时,处理反应器流时不会发生内置仪器,例如 6。spring-doc.cadn.net.cn

由于Spring Cloud Stream重用Spring Cloud Function,因此您将获得开箱即用的工具支持。spring-doc.cadn.net.cn

您可以通过将spring.sleuth.function.enabled值设置为false来禁用此行为。spring-doc.cadn.net.cn

要使用响应式流功能,您可以利用MessagingSleuthOperators实用程序类,它允许您操作输入和输出消息,以便继续跟踪上下文并执行自定义代码在跟踪上下文中。spring-doc.cadn.net.cn

class SimpleReactiveManualFunction implements Function<Flux<Message<String>>, Flux<Message<String>>> {

    private static final Logger log = LoggerFactory.getLogger(SimpleReactiveFunction.class);

    private final BeanFactory beanFactory;

    SimpleReactiveManualFunction(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Flux<Message<String>> apply(Flux<Message<String>> input) {
        return input.map(message -> (MessagingSleuthOperators.asFunction(this.beanFactory, message))
                .andThen(msg -> MessagingSleuthOperators.withSpanInScope(this.beanFactory, msg, stringMessage -> {
                    log.info("Hello from simple manual [{}]", stringMessage.getPayload());
                    return stringMessage;
                })).andThen(msg -> MessagingSleuthOperators.afterMessageHandled(this.beanFactory, msg, null))
                .andThen(msg -> MessageBuilder.createMessage(msg.getPayload().toUpperCase(), msg.getHeaders()))
                .andThen(msg -> MessagingSleuthOperators.handleOutputMessage(this.beanFactory, msg)).apply(message));
    }

}

4.3. Spring RabbitMq

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们对RabbitTemplate进行仪器,以便跟踪标头可以注入到消息中。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.messaging.rabbit.enabled 设置为 falsespring-doc.cadn.net.cn

4.4. Spring Kafka

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们对 Spring Kafka 的 ProducerFactoryConsumerFactory 进行仪器 te,以便跟踪头文件被注入到创建的 Spring Kafka 的 ProducerConsumer 中。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.messaging.kafka.enabled 设置为 falsespring-doc.cadn.net.cn

4.5. Spring Kafka Streams

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们对 KafkaStreams KafkaClientSupplier 进行仪器,以便跟踪标头被注入到 ProducerConsumer`s. A `KafkaStreamsTracing bean 中,允许通过其他 TransformerSupplierProcessorSupplier 方法进行进一步仪器。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.messaging.kafka.streams.enabled 设置为 falsespring-doc.cadn.net.cn

4.6。 Spring JMS

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们注入JmsTemplate,这样跟踪标头就会注入到消息中。
我们还支持@JmsListener在消费者端注释的方法。spring-doc.cadn.net.cn

阻止此功能,请将 spring.sleuth.messaging.jms.enabled 设置为 falsespring-doc.cadn.net.cn

我们不支持 JMS 的 baggage propagation

5. OpenFeign

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

默认情况下,Spring Cloud Sleuth 通过 TraceFeignClientAutoConfiguration 集成 Feign。 可以通过将 spring.sleuth.feign.enabled 设置为 false 来完全禁用它。 如果这样设置,就不会进行任何与 Feign 相关的仪器化。spring-doc.cadn.net.cn

部分Feign仪器是由FeignBeanPostProcessor完成的。您可以将其设置为spring.sleuth.feign.processor.enabled以禁用它。如果您将其设置为false,则Spring Cloud Sleuth不会对任何自定义Feign组件进行仪器。但是,所有默认仪器仍然存在。spring-doc.cadn.net.cn

6. OpenTracing

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

Spring Cloud Sleuth 与 OpenTracing 兼容。
如果类路径上有 OpenTracing,我们会自动注册 OpenTracing Tracer Bean。
如果你想禁用它,请将 spring.sleuth.opentracing.enabled 设置为 false
spring-doc.cadn.net.cn

7. Quartz

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们通过向Quartz调度器添加作业/触发器监听器来监控quartz作业。spring-doc.cadn.net.cn

要关闭此功能,请将spring.sleuth.quartz.enabled属性设置为falsespring-doc.cadn.net.cn

8. Reactor

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

我们有以下几种基于反应器的应用程序的仪器模式,可以通过spring.sleuth.reactor.instrumentation-type属性进行设置:spring-doc.cadn.net.cn

  • DECORATE_QUEUES - 随着新的 Reactor 队列包装机制 (Reactor 3.4.3),我们正在改进 Reactor 切换线程的方式。这应该能实现与 ON_EACH 的功能一致性,并且对性能影响较小。spring-doc.cadn.net.cn

  • DECORATE_ON_EACH - 将每个Reactor操作符包装为跟踪表示。在大多数情况下传递跟踪上下文。此模式可能导致性能急剧下降。spring-doc.cadn.net.cn

  • DECORATE_ON_LAST - 将最后一个Reactor操作符包装为跟踪表示形式。在某些情况下传递了跟踪上下文,因此访问MDC上下文可能无效。此模式可能导致中等程度的性能下降。spring-doc.cadn.net.cn

  • MANUAL - 以最小侵入性的方式包装Reactor中的每个组件,但不传递跟踪上下文。是否进行跟踪由用户自行决定。spring-doc.cadn.net.cn

当前默认值为 ON_EACH,出于向后兼容性原因,但我们鼓励用户迁移到 MANUAL 指标收集并从 WebFluxSleuthOperatorsMessagingSleuthOperators 中获益。
性能提升可能非常显著。
例如:
spring-doc.cadn.net.cn

@GetMapping("/simpleManual")
public Mono<String> simpleManual() {
    return Mono.just("hello").map(String::toUpperCase).doOnEach(WebFluxSleuthOperators
            .withSpanInScope(SignalType.ON_NEXT, signal -> log.info("Hello from simple [{}]", signal.get())));
}

9. Redis

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

我们将 tracing 属性设置为 Lettuce ClientResources 实例,以启用内置的 Brave 跟踪功能。spring-doc.cadn.net.cn

Spring Cloud Sleuth 将提供一个带有跟踪功能的 ClientResources bean。如果您有自己的该 bean 的实现,请记住使用如下面所示的 `ClientResourcesBuilderCustomizer` 流来定制 ClientResources.Builderspring-doc.cadn.net.cn

@Bean(destroyMethod = "shutdown")
DefaultClientResources myLettuceClientResources(ObjectProvider<ClientResourcesBuilderCustomizer> customizer) {
    DefaultClientResources.Builder builder = DefaultClientResources.builder();
    // setting up the builder manually
    customizer.stream().forEach(c -> c.customize(builder));
    return builder.build();
}

要禁用Redis支持,请将spring.sleuth.redis.enabled属性设置为falsespring-doc.cadn.net.cn

10. 可运行和可调用

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

如果你将逻辑包装在 RunnableCallable 中,你可以将这些类包装在其 Sleuth 代表类中,如下例所示 for Runnable:spring-doc.cadn.net.cn

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.tracer, spanNamer, runnable, "calculateTax");

下面的示例展示了如何执行此操作,对于Callablespring-doc.cadn.net.cn

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<>(tracer, spanNamer, callable, "calculateTax");

这样,您就确保为每次执行创建和关闭一个新的跨度。spring-doc.cadn.net.cn

11. 远程过程调用(RPC)

This feature is available for Brave tracer implementation.spring-doc.cadn.net.cn

跟踪器自动配置RpcTracing Bean,作为RPC仪器化的基础,例如gRPC或Dubbo。spring-doc.cadn.net.cn

如果需要自定义RPC跟踪的客户端/服务器采样,请注册一个类型为brave.sampler.SamplerFunction<RpcRequest>且名为sleuthRpcClientSampler的bean来表示客户端采样器,以及另一个名为sleuthRpcServerSampler的bean来表示服务器端采样器。spring-doc.cadn.net.cn

为了方便起见,@RpcClientSampler@RpcServerSampler 注解可用于注入适当的 bean 或通过其静态 String NAME 字段引用 bean 名称。spring-doc.cadn.net.cn

例如,以下采样器每秒跟踪100个“获取用户Tokens”服务器请求。对于健康检查服务的请求不会启动新跟踪。其他请求将使用全局采样配置。spring-doc.cadn.net.cn

@Configuration(proxyBeanMethods = false)
    class Config {
  @Bean(name = RpcServerSampler.NAME)
  SamplerFunction<RpcRequest> myRpcSampler() {
      Matcher<RpcRequest> userAuth = and(serviceEquals("users.UserService"), methodEquals("GetUserToken"));
      return RpcRuleSampler.newBuilder().putRule(serviceEquals("grpc.health.v1.Health"), Sampler.NEVER_SAMPLE)
              .putRule(userAuth, RateLimitingSampler.create(100)).build();
  }
}

有关更多信息,请参阅github.com/openzipkin/brave/tree/master/instrumentation/rpc#sampling-policyspring-doc.cadn.net.cn

11.1. Dubbo RPC 支持

通过与 Brave 的集成,Spring Cloud Sleuth 支持 Dubbo。只需要添加 brave-instrumentation-dubbo 依赖项:spring-doc.cadn.net.cn

<dependency>
    <groupId>io.zipkin.brave</groupId>
    <artifactId>brave-instrumentation-dubbo</artifactId>
</dependency>

还需要设置一个dubbo.properties文件,其内容如下所示:spring-doc.cadn.net.cn

dubbo.provider.filter=tracing
dubbo.consumer.filter=tracing

You can read more about Brave - Dubbo integration here. An example of Spring Cloud Sleuth and Dubbo can be found here.spring-doc.cadn.net.cn

11.2. gRPC

Spring Cloud Sleuth 提供了通过 Brave 追踪器对 gRPC 的仪器支持。您可以通过将 spring.sleuth.grpc.enabled 设置为 false 来完全禁用它。spring-doc.cadn.net.cn

11.2.1. 变体 1

依赖项
Spring框架的gRPC集成依赖于两个外部库来对客户端和服务端进行仪器检测,为了启用仪器检测,这两个外部库都必须在类路径上。
        <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>
    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 注解的服务进行注册。spring-doc.cadn.net.cn

客户端仪器

gRPC 客户端利用 ManagedChannelBuilder 构建用于与 gRPC 服务器通信的 ManagedChannel。原生 ManagedChannelBuilder 提供了静态方法作为构建 ManagedChannel 实例的入口点,但此机制不受 Spring 应用上下文的影响。spring-doc.cadn.net.cn

Spring Cloud Sleuth 提供了一个 SpringAwareManagedChannelBuilder,可以通过 Spring 应用上下文进行定制,并由 gRPC 客户端注入。

spring-doc.cadn.net.cn

当创建 ManagedChannel 实例时必须使用此构建器。spring-doc.cadn.net.cn

跟踪器创建一个TracingManagedChannelBuilderCustomizer,并将Brave的客户端拦截器注入到SpringAwareManagedChannelBuilder中。spring-doc.cadn.net.cn

11.2.2. 变体 2

Grpc Spring Boot Starter 自动检测 Spring Cloud Sleuth 和 brave 的 gRPC 检测,并注册必要的客户端和/或服务器工具。spring-doc.cadn.net.cn

12. RxJava

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

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-doc.cadn.net.cn

你可以为线程名称定义一个列表,对于这些名称,您不想创建跨度。要实现这一点,请在spring.sleuth.rxjava.schedulers.ignoredthreads属性中提供由逗号分隔的正则表达式列表。spring-doc.cadn.net.cn

建议的响应式编程和Sleuth的方法是使用Reactor支持。

13. Spring Cloud CircuitBreaker

此功能对所有跟踪程序实现均可用。spring-doc.cadn.net.cn

如果类路径中包含 Spring Cloud CircuitBreaker,我们将传递的命令Supplier和回退Function包装在其跟踪表示形式中。为了禁用此仪器设置spring.sleuth.circuitbreaker.enabledfalsespring-doc.cadn.net.cn