![](/img/trans.png)
[英]Javascript is not called from RequestContext in ManagedBean
[英]Accessing StreamListener headers from RequestContext or similar
我有一項服務,可以撥打其他十幾項服務。 這將使用控制器類中的@StreamListener
從Kafka主題中讀取。 出於可追溯性目的,需要將來自Kafka消息的相同標頭(原始請求ID)轉發到所有其他服務
傳統上,使用@PostMapping("/path")
或GetMapping
,會生成一個請求上下文,並且可以使用RequestContextHolder.currentRequestAttributes()
從任何地方訪問頭文件,我只需要在需要時將HttpHeaders
對象傳遞給RequestEntity
撥打外部電話
但是,在StreamListener
,不會生成任何請求上下文,並且嘗試訪問RequestContextHolder
導致異常
這是我嘗試做的一個例子,這導致了一個例外:
public class Controller {
@Autowired Service1 service1
@Autowired Service2 service2
@StreamListener("stream")
public void processMessage(Model model) {
service1.execute(model);
service2.execute(model);
}
}
public class Service {
RestTemplate restTemplate;
public void execute(Model model){
// Do some stuff
HttpHeaders httpHeaders = RequestContextHolder.currentRequestAttributes().someCodeToGetHttpHeaders();
HttpEntity<Model> request = new HttpEntity(model, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, request, String.class);
}
}
我目前的解決方法是將StreamListener
更改為PostMapping
並使用另一個調用它的PostMapping
,以便生成請求上下文。 另一個選擇是使用ThreadLocal
但它看起來像janky一樣
我知道@Headers MessageHeaders
注釋可以訪問流標題,但是,如果不將標題傳遞給每個服務並且會影響許多單元測試,則無法輕松訪問
理想情況下,我需要一種方法來創建我自己的請求上下文(或任何適當的術語),以便有一個存儲請求范圍對象( HttpHeader
)的地方或另一種線程安全的方式,讓請求頭傳遞到堆棧而不添加請求service.execute
參數
我找到了一個解決方案,並將其留在這里為其他任何試圖實現類似功能的人
如果您的目標是通過REST控制器和Stream偵聽器端到端地轉發一堆標頭,您可能需要考慮使用Spring Cloud Sleuth
通過maven或gradle配置將其添加到項目中:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
具體來說,在Spring Cloud Sleuth中,通過在spring.sleuth.propagation-keys
設置屬性spring.sleuth.propagation-keys
,可以轉發標題或“行李”。 這些鍵值對在整個跟蹤中保持不變,包括任何下游http或流調用,這些調用也實現相同的傳播密鑰
如果需要在代碼級別訪問這些字段,則可以使用ExtraFieldPropagation
靜態函數來獲取和設置它們:
ExtraFieldPropagation.set("country-code", "FO"); // Set
String countryCode = ExtraFieldPropagation.get("country-code"); // Get
請注意, ExtraFieldPropagation
setter無法設置定義的spring.sleuth.propagation-keys
不存在的屬性,因此不會接受任意鍵
您可以閱讀文檔以獲取更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.