1 背景
服務(wù)調(diào)用層級很多,如何快速定位故障祠肥,處理異常武氓。
某個(gè)用戶報(bào)響應(yīng)很慢,怎么排查仇箱?
某筆業(yè)務(wù)交易出現(xiàn)異常县恕,怎么分析?
怎么防止推諉扯皮剂桥,互相甩鍋忠烛?
2 理論依據(jù)--Google Dapper
http://bigbully.github.io/Dapper-translation/
方案基本思路是在服務(wù)調(diào)用的請求、響應(yīng)中加入跟蹤ID--traceid权逗,traceid用于唯一標(biāo)識一次鏈路調(diào)用美尸。怎么實(shí)現(xiàn)的呢?邏輯很簡單斟薇,參與者實(shí)現(xiàn)在httpheader中加入traceid信息师坎,通過httpheader傳輸,如果存在則沿用發(fā)起者的traceid堪滨,否則新建胯陋。
標(biāo)識服務(wù)調(diào)用上下游關(guān)系,通過代表自身節(jié)點(diǎn)id的--spanid袱箱,代表父節(jié)點(diǎn)的parentid遏乔。從而將整個(gè)鏈路串聯(lián)起來。
可集合的信息包括:traceid发笔,spanid盟萨,url,httpcode了讨,exception等捻激,用戶還可以自定義字段制轰。
對于調(diào)用端來說:發(fā)出請求的時(shí)間戳,收到信息的時(shí)間戳铺罢;
對于服務(wù)端來說:收到請求的時(shí)間戳艇挨、處理完響應(yīng)時(shí)間戳残炮。
貼一張鏈路跟蹤處理流程圖:
3 實(shí)現(xiàn)方案
現(xiàn)成的方案:pinpoint韭赘、zipkin、阿里鷹眼势就、大眾CAT
各個(gè)方案的優(yōu)缺點(diǎn):
pinpoint 字節(jié)碼注入泉瞻,對代碼完全無侵入,在部署的時(shí)候java -jar pinpoint苞冯。缺點(diǎn)是生態(tài)不大好袖牙,個(gè)性化較弱,只支持java
zipkin:代碼侵入較低舅锄,侵入到:配置文件鞭达、攔截器。生態(tài)好皇忿,多語言客戶端畴蹭,個(gè)性化較強(qiáng)
阿里鷹眼:牛逼但閉源,高級功能較多鳍烁,沒啥好講的叨襟。人傻錢多速來買
cat:侵入性最強(qiáng),不建議使用幔荒。
綜上所述糊闽,選zipkin。
官方github:https://github.com/openzipkin/zipkin
3.1 架構(gòu)圖
reporter:zipkin客戶端爹梁,沒有實(shí)現(xiàn)reporter的應(yīng)用當(dāng)然推不了鏈路監(jiān)控?cái)?shù)據(jù)了右犹。
transport:http 、kafka姚垃,生產(chǎn)環(huán)境用kafka傀履,異步解耦高性能
collector:zipkin-server后臺任務(wù),接收處理鏈路監(jiān)控?cái)?shù)據(jù)
storage:內(nèi)存莉炉、Cassandra钓账、ES、mysql絮宁,推薦用ES
api&ui:ui查詢分析工具
可用于生產(chǎn)環(huán)境的架構(gòu): brave + kafka + zipkin server +es
理由 為何不選spring cloud sleuth,有點(diǎn)厭惡過渡封裝梆暮,出了問題難以排查,對于生產(chǎn)環(huán)境并不是足夠穩(wěn)定绍昂。brave足夠簡單直接啦粹,個(gè)性化定制能力很強(qiáng)偿荷。
為何不用http來傳輸span跟蹤信息?做監(jiān)控唠椭,應(yīng)當(dāng)盡量不影響正常的業(yè)務(wù)代碼運(yùn)行跳纳,監(jiān)控代碼不要與業(yè)務(wù)代碼耦合在一起,為什么呢贪嫂?保證可讀性寺庄,將來遷移改造很便利,保證業(yè)務(wù)代碼是獨(dú)立純粹的力崇,同理不能與常見的日志斗塘,異常,參數(shù)檢驗(yàn)等耦合亮靴。
kafka的有點(diǎn)馍盟,異步高并發(fā)高性能解耦。
為何選es茧吊,而不是MySQL或者cassandra.日志采集量大贞岭,一天上億條輕輕松松,一定要具備大容量搓侄,便于做日志聚合分析瞄桨,es絕對首選。而且我們的技術(shù)棧也是采用了elk搭建日志體系休讳。便于與業(yè)務(wù)日志聚合讲婚。
4 zipkin客戶端:Brave
數(shù)據(jù)推送方式:HTTP KAFKA scribe
TraceContext中有以下一些屬性
traceIdHigh - 唯一標(biāo)識trace的16字節(jié)id,即128-bit
traceId - 唯一標(biāo)識trace的8字節(jié)id
parentId - 父級Span的spanId
spanId - 在某個(gè)trace中唯一標(biāo)識span的8字節(jié)id
shared - 如果為true俊柔,則表明需要從其他tracer上共享span信息
extra - 在某個(gè)trace中相關(guān)的額外數(shù)據(jù)集
4 與springboot集成
詳細(xì)代碼參考:https://github.com/wuzuquan/microservice
4.1引入jar包
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-context-slf4j</artifactId>
<version>4.9.1</version>
<exclusions>
<exclusion>
<artifactId>zipkin</artifactId>
<groupId>io.zipkin.java</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.zipkin.reporter2</groupId>
<artifactId>zipkin-sender-kafka11</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-instrumentation-okhttp3</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>io.zipkin.brave</groupId>
<artifactId>brave-instrumentation-spring-webmvc</artifactId>
<version>4.9.1</version>
</dependency>
4.2初始化zipkin 客戶端配置
初始化一個(gè)kafkasender筹麸,對httptracing做一些個(gè)性化配置
@Autowired
private ZipkinProperties zipkinProperties;
@Bean
KafkaSender sender() {
Map<String, String> pro = new HashMap<>();
pro.put("acks", "1");
// pro.put("linger.ms","50");
pro.put("retries", "1");
// pro.put("compression.type","gzip");
// pro.put("producer.type","async");
return KafkaSender.newBuilder().overrides(pro)
.bootstrapServers(zipkinProperties.getKafkaHosts())
.topic(zipkinProperties.getTopic())
.encoding(Encoding.PROTO3)
.build();
}
@Bean
AsyncReporter<Span> spanReporter() {
return AsyncReporter.builder(sender())
.closeTimeout(500, TimeUnit.MILLISECONDS)
.messageMaxBytes(200000)
.queuedMaxSpans(500)
.build();
}
@Bean
Tracing tracing() {
return Tracing.newBuilder()
.localServiceName(zipkinProperties.getServiceName())
.sampler(Sampler.ALWAYS_SAMPLE)
.propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
.currentTraceContext(MDCCurrentTraceContext.create()) // puts trace IDs into logs
.spanReporter(spanReporter()).build();
}
@Bean
HttpTracing httpTracing(Tracing tracing) {
return HttpTracing.newBuilder(tracing)
.clientParser(new HttpClientParser() {
@Override
protected <Req> String spanName(HttpAdapter<Req, ?> adapter, Req req) {
return adapter.url(req).toString();
}
@Override
public <Req> void request(HttpAdapter<Req, ?> adapter, Req req, SpanCustomizer customizer) {
customizer.name(spanName(adapter, req)); // default span name
customizer.tag("url", adapter.url(req)); // the whole url, not just the path
super.request(adapter, req, customizer);
}
})
.serverParser(new HttpServerParser() {
@Override
protected <Req> String spanName(HttpAdapter<Req, ?> adapter, Req req) {
return adapter.url(req).toString();
}
@Override
public <Req> void request(HttpAdapter<Req, ?> adapter, Req req, SpanCustomizer customizer) {
customizer.name(spanName(adapter, req)); // default span name
customizer.tag("url", adapter.url(req)); // the whole url, not just the path
super.request(adapter, req, customizer);
}
})
.build();
}
初始化完后在webconfig中配置tracing攔截器,當(dāng)別人來調(diào)我的服務(wù)時(shí)雏婶,此時(shí)是server的角色物赶,記錄 server receive 、server send信息
在resttemplate中配置tracing攔截器留晚,去調(diào)別人的http服務(wù)的時(shí)候酵紫,此時(shí)是client角色,記錄client send错维、client receive信息
4.3在webconfig中配置攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(serverZipkinInterceptor)
.excludePathPatterns("/metrics/**")
.excludePathPatterns("/v2/api-docs","/configuration/**","/swagger-resources/**");
registry.addInterceptor(new PrometheusMetricsInterceptor()).addPathPatterns("/**");
}
4.4 在resttemplate中配置
resttemplate可用httpclient奖地、okhttp、netty初始化赋焕,我們選用的是okhttp参歹。
看看okhttp怎么初始化的吧
@Bean
public OkHttpClient okHttpClient() {
//注意:使用http2.0協(xié)議,只有明確知道服務(wù)端支持H2C協(xié)議的時(shí)候才能使用隆判。添加H2C支持犬庇,
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE));
Dispatcher dispatcher=new Dispatcher(
httpTracing.tracing().currentTraceContext()
.executorService(new Dispatcher().executorService())
);
//設(shè)置連接池大小
dispatcher.setMaxRequests(1000);
dispatcher.setMaxRequestsPerHost(200);
ConnectionPool pool = new ConnectionPool(20, 30, TimeUnit.MINUTES);
builder.connectTimeout(250, TimeUnit.MILLISECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.connectionPool(pool)
.dispatcher(dispatcher)
//鏈路監(jiān)控埋點(diǎn)
.addNetworkInterceptor(TracingInterceptor.create(httpTracing))
//.addInterceptor(new OkHttpInterceptor())
.retryOnConnectionFailure(false);
return builder.build();
}
RestTemplate restTemplate= new RestTemplate(OkHttp3Factory());
4.5 數(shù)據(jù)處理過程
并不是每來一個(gè)span數(shù)據(jù)就往kafka推僧界,這樣效率必然是最差的。
批量優(yōu)化處理嘛臭挽,內(nèi)存建一個(gè)span隊(duì)列捂襟,當(dāng)堆積的量達(dá)到設(shè)定的最大值,一次性往kafka推span數(shù)組欢峰。
zipkinserver監(jiān)聽kafka“zipkin”這個(gè)topic葬荷。收到span數(shù)組后,進(jìn)行拆分赤赊,索引闯狱,校驗(yàn)等操作煞赢,再調(diào)ES的restful接口寫入ES抛计。
zipkinserver提供的查詢分析工具就可以去ES取數(shù)據(jù),進(jìn)行鏈路監(jiān)控分析了照筑。
5 融合ELK日志體系
單單只有zipkin的數(shù)據(jù)還是不夠的吹截,zipkin的作用是將一個(gè)完整的調(diào)用鏈路串聯(lián)起來。但缺乏詳細(xì)的業(yè)務(wù)日志信息凝危,怎么搞波俄?
每個(gè)brave tracing會把traceid spanid等信息插入 MDC,實(shí)現(xiàn)了標(biāo)準(zhǔn)日志接口的日志工具既可以從MDC中讀取traceid蛾默,在log.info中將traceid一并寫入懦铺,從而將鏈路與每個(gè)服務(wù)的業(yè)務(wù)日志關(guān)聯(lián)起來。
我要記錄DB\MQ\NOSQL的日志能支持嗎支鸡?對不起我不支持冬念,把zipkin定位于一個(gè)純粹的串聯(lián)鏈路工具,不與業(yè)務(wù)代碼耦合牧挣。
log.info會支持就好急前。
我們記錄的結(jié)構(gòu)化log數(shù)據(jù)格式:
LogEntity logEntity=new LogEntity();
logEntity.setTraceId(MDC.get("traceId"));
logEntity.setSpanId(MDC.get("spanId"));
logEntity.setIP(ip);
logEntity.setAppName(getAppname());
logEntity.setLevel(event.getLevel().levelStr);
logEntity.setLogger(event.getLoggerName());
logEntity.setLocation(event.getCallerData()[0].toString());
logEntity.setTimestamp(LocalDateTime.now());
logEntity.setMessage(event.getFormattedMessage());
代碼詳解core模塊下的logback+kafka相關(guān)配置與數(shù)據(jù)結(jié)構(gòu)