Spring Cloud Stream message from/to JSON conversion configuration

旧巷老猫 提交于 2019-12-01 03:48:45

问题


I am using Spring Cloud Stream, with RabbitMQ binder. It works great with byte[] payload and Java native serialization, but I need to work with JSON payload.

Here's my processor class.

@EnableBinding(Processor.class)
public class MessageProcessor {
    @ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
    public OutputDto handleIncomingMessage(InputDto inputDto) {
        // Run some job.
        return new OutputDto();
    }
}

InputDto and OutputDto are POJOs with Jackson annotations.

  • How do I configure JSON conversion strategy?
  • How should message headers look like to be accepted and processed?

回答1:


In your consumer you can add a content type configuration, e.g.

spring.cloud.stream.bindings.input.content-type: application/x-java-object;type=my.package.InputDto

You could also add

spring.cloud.stream.bindings.output.content-type: application/json

to force the outgoing message payload to be JSON (for interop etc.).

Note that "input" and "output" are the binder channel names (i.e. as defined in Processor in your app).

I think there is a good chance this could be made easier or more automatic, but there is some engineering effort required to make that happen in Spring Cloud. There's an issue in github if you want to follow it: https://github.com/spring-cloud/spring-cloud-stream/issues/156.

To send a message manually to a Spring Cloud Stream you can set the headers up yourself manually (but it's easier to use a Stream). A JSON message looks like this in the Rabbit admin UI:

priority:   0
delivery_mode:  2
headers:    
    contentType:    text/plain
    originalContentType:    application/json
content_type:   text/plain


来源:https://stackoverflow.com/questions/35500759/spring-cloud-stream-message-from-to-json-conversion-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!