使用 Spring Cloud Sleuth 3.1.4 版,我想在 HTTP 回應標頭中插入跟蹤 ID。我創建了一個 GlobalFilter 型別的 bean 并嘗試檢索跟蹤 ID 字串,如下所示
@Configuration
public class ResponseFilter {
@Autowired
Tracer tracer;
@Autowired
FilterUtils filterUtils;
final Logger logger =LoggerFactory.getLogger(ResponseFilter.class);
@Bean
public GlobalFilter postGlobalFilter() {
return (exchange, chain) -> {
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
String traceId = tracer.currentSpan().context().traceIdString();
logger.debug("Adding the correlation id to the outbound headers. {}", traceId);
exchange.getResponse().getHeaders().add(FilterUtils.CORRELATION_ID, traceId);
logger.debug("Completing outgoing request for {}.", exchange.getRequest().getURI());
}));
};
}
}
我得到tracer.currentSpan()了 NULL 這就是為什么它為上述代碼提供 NPE。
uj5u.com熱心網友回復:
問題是 currentSpan 將在 then() 方法中過期,而當您想要獲取它時,它根本不存在。因此,您應該盡早服用。
這是一個解決方案,您可以在其中獲取當前跨度并檢索 traceId:
@Bean
public GlobalFilter postGlobalFilter() {
return (exchange, chain) -> {
final String traceId = Optional.ofNullable(tracer.currentSpan())
.map(Span::context)
.map(TraceContext::traceIdString)
.orElse("null");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
logger.debug("Adding the correlation id to the outbound headers. {}", traceId);
exchange.getResponse().getHeaders().add(FilterUtils.CORRELATION_ID, traceId);
logger.debug("Completing outgoing request for {}.",
exchange.getRequest().getURI());
}));
};
}
請注意,我使用 Java 的 Optional 來處理空值。您也可以使用 Mono.just(...).map(...).switchIfEmpty(...) 。
這是配置 Spring Cloud Gateway 過濾器的一種更簡潔的方法:
@Slf4j
@Configuration
@Profile({"dev","stage"})
@RequiredArgsConstructor
public class ResponseFilter implements GlobalFilter {
private final Tracer tracer;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
final String traceId = Optional.ofNullable(tracer.currentSpan())
.map(Span::context)
.map(TraceContext::traceIdString)
.orElse("null");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.debug("Adding the correlation id to the outbound headers. {}", traceId);
exchange.getResponse().getHeaders().add(FilterUtils.CORRELATION_ID, traceId);
log.debug("Completing outgoing request for {}.",
exchange.getRequest().getURI());
}));
}
}
請記住,在網關的 http 回應中公開 traceId 通常不是一個好主意(根據 Spring Cloud Sleuth 檔案),除非您處于開發或階段并且想要將其用于除錯目的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/520513.html
上一篇:OAuth2身份驗證服務器訪問令牌從JWT令牌到OAuth令牌
下一篇:使用Map<String,Object>而不是org.springframework.ui.Model來填充視圖
