2017-04-03 66 views
0

我們正在構建基於Apache Camel的消息路由器,並決定使用多種格式的通用流。我們通過一個通用的休息端點輸入我們的消息,並有條件地將此呼叫的主體映射到多種特定消息格式中的一種。我們從不同的XSD生成了我們特定的數據格式。如何將頭字符串傳遞給駱駝服務

映射發生在處理器中,處理器依賴於消息的內容使用不同的映射器。該處理器將特定的Java模型放入交換機的主體中。

在接下來的步驟中,我們希望將身體編組並驗證XML。這是一個「通用」步驟,因爲所有消息都必須編組爲XML。之後,他們會再次根據消息內容發送到動態端點。

元帥我們用下面的路線XML:

from("direct:marshal-xml") 
.marshal(jaxbDataFormat) 
.to("direct:validate-and-send"); 

根據所謂的「爲messageType」的標題屬性,我們想用一個不同的jaxbDataFormat對象編組爲XML。我們可以在路由本身中做出選擇,但我們希望使用一個專門的服務,它接受一個字符串輸入messageType,並返回正確的jaxbDataFormat。

現在的問題是如何將頭文件屬性「messageType」作爲參數傳遞給服務。我們想用類似的東西:

from("direct:marshal-xml") 
.marshal(jaxbDataFormatService.getDataFormat(getHeader("messageType"))) 
.to("direct:validate-and-send"); 

但我似乎無法從頭中獲取messageType作爲字符串。路由建模器(它對路由進行「建模」)與從此模型生成的運行時路由之間似乎存在差異。

我試圖用簡單的expresions,但我似乎無法評估他們沒有交換:

simple("${header.messageType}").evaluate(exchange, String.class); 

如何解決這個問題呢?我是否必須在routebuilder中使用選擇組件,還是有可能仍然使用此專用服務?

回答

2

您可以始終實現您自己的「複合數據格式」,例如通過實施org.apache.camel.spi.DataFormat來獲得您想要使用的所有數據格式,並使用您想要的數據格式。

這樣的事情,只是給你一個想法:

public class MyCompositeFormat implements DataFormat, CamelContextAware { 

    public MyCompositeFormat(DataFormat... formats) { 
     // store them to local variable 
    } 

    public CamelContext getCamelContext() { 
     return camelContext; 
    } 

    public void setCamelContext(CamelContext camelContext) { 
     this.camelContext = camelContext; 
    } 

    public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { 
     if (exchange.getIn().getHeader("SomeHeader",String.class).equals("whatever") { 
     return someFormatYouStored.marshal(exchange,graph,stream); 
     } else { 
     return anotherFormat.marshal(exchange,graph,stream); 
     } 

    } 

    public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { 
     // similar approach to marshal 
    } 

} 

而在你的路線:

MyCompositeFormat myCompositeFormat = new MyCompositeFormat(otherFormats); 
from("direct:marshal-xml") 
.marshal(myCustomFormat) 
.to("direct:validate-and-send"); 
+0

感謝您的快速和非常有用的回覆!我沒有實現我自己的DataFormat。這完全符合我們的需求! – Stijnvdk