1. maven依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.2</version></parent><properties><java.version>21</java.version><spring-cloud.version>2022.0.4</spring-cloud.version><spring-boot-admin.version>3.1.2</spring-boot-admin.version></properties><dependencies><!-- 链路追踪 多服务使用--><dependency><groupId>io.micrometer</groupId><artifactId>micrometer-tracing-bridge-brave</artifactId></dependency><dependency><groupId>io.zipkin.reporter2</groupId><artifactId>zipkin-reporter-brave</artifactId></dependency><dependency><groupId>io.zipkin.brave</groupId><artifactId>brave-instrumentation-grpc</artifactId></dependency></dependencies>
2. 配置类
假设有grpc服务A和B,之间相互调用,那么这两个服务都要配置如下
import brave.Tracing;
import brave.grpc.GrpcTracing;
import io.grpc.ClientInterceptor;
import io.grpc.ServerInterceptor;
import net.devh.boot.grpc.server.interceptor.GlobalServerInterceptorConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zipkin2.Span;
import zipkin2.reporter.Reporter;@Configuration
public class GrpcZipkinConfig {private static final Logger logger = LoggerFactory.getLogger(GrpcZipkinConfig.class);@Beanpublic GrpcTracing grpcTracing(Tracing tracing) {return GrpcTracing.create(tracing);}//grpc-spring-boot-starter provides @GrpcGlobalInterceptor to allow server-side interceptors to be registered with all//server stubs, we are just taking advantage of that to install the server-side gRPC tracer.@BeanServerInterceptor grpcServerSleuthInterceptor(GrpcTracing grpcTracing) {return grpcTracing.newServerInterceptor();}//We also create a client-side interceptor and put that in the context, this interceptor can then be injected into gRPC clients and//then applied to the managed channel.@BeanClientInterceptor grpcClientSleuthInterceptor(GrpcTracing grpcTracing) {return grpcTracing.newClientInterceptor();}// Use this for debugging (or if there is no Zipkin server running on port 9411)@Bean@ConditionalOnProperty(value = "sample.zipkin.enabled", havingValue = "false")public Reporter<Span> spanReporter() {return new Reporter<Span>() {@Overridepublic void report(Span span) {logger.info("{}",span);}};}@Beanpublic GlobalServerInterceptorConfigurer globalInterceptorConfigurerAdapter(ServerInterceptor grpcServerSleuthInterceptor) {return registry -> registry.add(grpcServerSleuthInterceptor);}
}
3. 启动参数
logging:pattern:level: '%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]'