2016-03-15 20 views
1

我跟着我的上一個問題Spring Cloud Stream message from/to JSON conversion configuration和配置的流如上所述,但我無法使其正常工作。Spring雲流消息JSON轉換不起作用

我的設置如下。我有兩個應用程序AB。應用A使用輸入通道one,輸出two。 App B使用輸入two。頻道two配置了內容類型application/json

App A. Properties。

spring.cloud.stream.bindings.input.destination=one 
spring.cloud.stream.bindings.input.group=default 

spring.cloud.stream.bindings.output.destination=two 
spring.cloud.stream.bindings.output.content-type=application/json 

監聽方法。

@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) 
public Dto handle(byte[] payload) throws IOException { 
    final Dto dto = new ObjectMapper().readValue(payload, Dto.class); 
    logger.info("{}", dto); 
    dto.setId(dto.getId() + 1000); 
    return dto; 
} 

App B. Properties。

spring.cloud.stream.bindings.input.destination=two 
spring.cloud.stream.bindings.input.group=default 
spring.cloud.stream.bindings.input.content-type=application/json 

聽衆的方法。

@ServiceActivator(inputChannel = Sink.INPUT) 
public void handle(Dto dto) throws IOException { 
    logger.info("DTO {}", dto); 
} 

當我手動發送的消息與適當的JSON字符串到通道one,它被正確地處理併發送的信道two作爲JSON消息(頭如在上面提到的問題中所述完全相同的)。在此之後,它是由應用程序B接收信道two並拋出異常:Method handle(java.lang.String) cannot be found

當然,當我創建這兩種方法,處理DTO和字符串作爲輸入,它的工作原理,但總是字符串方法被調用,並有反序列化我自己的有效載荷。

我誤會了嗎?如何設置帶有這種簽名的方法:public Dto handle(Dto incoming)

+0

爲什麼你不使用'StreamListener'而不是'ServiceActivator'作爲你的App B?我不是100%確定的,但我認爲你的問題可以通過'StreamListener'修復,而不是改變'content-type'屬性。 – Gooseman

+0

當時,此類選項不可用。但是,是的,這是一個很好的建議。 – waste

回答

1

你應該APPB輸入的內容類型說明更改爲

application/x-java-object;type=your.package.Dto

因爲它是在你的問題中指定的,當然你只接受JSON字符串。

+0

我不需要Java序列化。看看這個主題 - 我需要JSON消息。 – waste

+0

確實,您將使AppA輸出的內容類型聲明具有JSON輸出,但應通過此內容類型聲明告知AppB,相應的MessageConverter應將有效內容轉換爲Dto對象。在調試過程中可以看到,通道上的消息將是JSON。 – Alexander

+0

這真的有用,謝謝。考慮到其他Spring組件的工作原理(AMQP或Rest),令人難以置信的不直觀。 – waste