Java Spring云数据流消息JSON转换不工作
我按照前面的问题进行了配置,但无法使其正常工作 我的设置如下。我有两个应用程序Java Spring云数据流消息JSON转换不工作,java,json,spring-cloud-stream,Java,Json,Spring Cloud Stream,我按照前面的问题进行了配置,但无法使其正常工作 我的设置如下。我有两个应用程序A和B。应用程序A使用输入通道1,输出通道2。应用程序B使用输入2。频道two配置了内容类型application/json 应用A.属性 spring.cloud.stream.bindings.input.destination=one spring.cloud.stream.bindings.input.group=default spring.cloud.stream.bindings.output.dest
A
和B
。应用程序A
使用输入通道1
,输出通道2
。应用程序B
使用输入2
。频道two
配置了内容类型application/json
应用A.属性
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
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 = 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;
}
@ServiceActivator(inputChannel = Sink.INPUT)
public void handle(Dto dto) throws IOException {
logger.info("DTO {}", dto);
}
附录B.属性
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
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 = 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;
}
@ServiceActivator(inputChannel = Sink.INPUT)
public void handle(Dto dto) throws IOException {
logger.info("DTO {}", dto);
}
当我手动将带有正确JSON字符串的消息发送到通道one
,它将被正确处理并作为JSON消息发送到通道two
(标题与上述问题中所述完全相同)。之后,应用程序B在通道two
上接收到它,并抛出异常:方法句柄(java.lang.String)找不到
当然,当我创建这两个方法时,将Dto和String作为输入处理,它是有效的,但总是调用String方法,并且必须自己反序列化负载
我在什么地方弄错了吗?如何设置具有此类签名的方法:
公共Dto句柄(Dto传入)
?您应该将AppB输入的内容类型声明更改为
application/x-java-object;type=your.package.Dto
正如您的问题中所指定的,您当然只接受JSON字符串。如果使用@StreamListener,您不必使用答案方式,但必须删除(不要指定任何内容,否则它将是JSON字符串): 来自AppB属性 来源(旧文档但仍然有效):
我不需要Java序列化。看一看主题——我需要JSON消息。没错,您可以将AppA输出的内容类型声明保留为JSON输出,但是应该通过此内容类型声明告知AppB,一个相应的MessageConverter应该将负载转换为Dto对象。在调试过程中可以看到,通道上的消息将是JSON。这确实有效,谢谢。考虑到其他Spring组件(AMQP或Rest)的工作方式,难以置信的不直观。为什么你不为你的应用程序B使用
StreamListener
而不是ServiceActivator
?我不是100%确定,但我认为可以使用StreamListener
而不是更改content-type
属性来解决您的问题。当时,该选项不可用。但是,是的,这是一个很好的建议。