SpringCloud 手動(dòng)設(shè)置范圍

2023-12-01 15:57 更新

編寫新工具時(shí),將您創(chuàng)建的跨度作為當(dāng)前跨度放置在示波器中很重要。這樣做不僅使用戶可以使用Tracer.currentSpan()訪問它,而且還允許自定義文件(例如SLF4J MDC)查看當(dāng)前的跟蹤ID。

Tracer.withSpanInScope(Span)促進(jìn)了這一點(diǎn),并且通過使用try-with-resources慣用法最方便地使用。每當(dāng)可能調(diào)用外部代碼(例如進(jìn)行攔截器或其他操作)時(shí),請(qǐng)將范圍放在范圍內(nèi),如以下示例所示:

@Autowired Tracer tracer;

try (SpanInScope ws = tracer.withSpanInScope(span)) {
  return inboundRequest.invoke();
} finally { // note the scope is independent of the span
  span.finish();
}

在極端情況下,您可能需要臨時(shí)清除當(dāng)前跨度(例如,啟動(dòng)不應(yīng)與當(dāng)前請(qǐng)求關(guān)聯(lián)的任務(wù))。為此,請(qǐng)將null傳遞給withSpanInScope,如以下示例所示:

@Autowired Tracer tracer;

try (SpanInScope cleared = tracer.withSpanInScope(null)) {
  startBackgroundThread();
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)