55. 将 spans 发送到 Zipkin

spring-cloud-sleuth-stream已弃用,不应再使用。如果spring-cloud-sleuth-zipkin在 classpath 上,则应用程序将生成并收集 Zipkin-compatible 跟踪。默认情况下,它通过 HTTP 将它们发送到 localhost(port 9411)上的 Zipkin 服务器。如果您依赖spring-rabbitspring-kafka,您的应用程序会将痕迹发送到 broker 而不是 http。

默认情况下,如果将spring-cloud-starter-zipkin作为依赖项添加到项目中,则当 span 关闭时,它将通过 HTTP 发送到 Zipkin。通信是异步的。您可以通过设置spring.zipkin.baseUrl property 来配置 URL,如下所示:

spring.zipkin.baseUrl: http://192.168.99.100:9411/

如果你想通过服务发现找到 Zipkin,它就足以在 URL 中传递 Zipkin 的服务 ID。如果要禁用此 feature,只需将spring.zipkin.discoveryClientEnabled设置为false. Example for zipkinserver`服务 ID:

spring.zipkin.baseUrl: http://zipkinserver/

启用此 Discovery Client feature 后,Sleuth 使用LoadBalancerClient查找 Zipkin 服务器的 URL。这意味着您可以设置负载平衡 configuration e.g. 通过 Ribbon。

zipkinserver:
  ribbon:
    ListOfServers: host1,host2

如果在 classpath 上有 web,rabbit 或 kafka,则可能需要选择将 spans 发送到 zipkin 的方法。要做到这一点,只需将webrabbitkafka设置为spring.zipkin.sender.type property 即可。 _示例web

spring.zipkin.sender.type: web

要自定义通过 HTTP 将 spans 发送到 Zipkin 的RestTemplate,您可以注册ZipkinRestTemplateCustomizer bean。

@Configuration
class MyConfig {
	@Bean ZipkinRestTemplateCustomizer myCustomizer() {
		return new ZipkinRestTemplateCustomizer() {
			@Override
			void customize(RestTemplate restTemplate) {
				// customize the RestTemplate
			}
		};
	}
}

但是,如果要控制创建RestTemplate object 的完整 process,则必须创建一个zipkin2.reporter.Sender类型的 bean。

@Bean Sender myRestTemplateSender(ZipkinProperties zipkin,
			ZipkinRestTemplateCustomizer zipkinRestTemplateCustomizer) {
		RestTemplate restTemplate = mySuperCustomRestTemplate();
		zipkinRestTemplateCustomizer.customize(restTemplate);
		return myCustomSender(zipkin, restTemplate);
	}