java - Spring Cloud Stream 消息 JSON 转换不起作用

标签 java json spring-cloud-stream

我关注了我之前的问题 Spring Cloud Stream message from/to JSON conversion configuration并按照描述配置流,但是,我无法使其正常工作。

我的设置如下。我有两个应用程序 AB。应用 A 使用输入 channel one,输出 two。应用 B 使用输入 two。 channel 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

监听器方法。

@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;
}

应用 B. 属性。

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 字符串的消息发送到 channel one 时,它被正确处理并作为 JSON 消息发送到 channel two( header 与在上述问题中描述)。之后,应用程序 B 在 channel two 上接收到它并抛出异常:Method handle(java.lang.String) cannot be found

当然,当我创建这两个方法时,将 Dto 和 String 作为输入处理,它可以工作,但总是调用 String 方法并且必须自己反序列化有效负载。

我是不是哪里弄错了?我如何使用这样的签名设置方法:public Dto handle(Dto incoming)

最佳答案

您应该将 AppB 输入的内容类型声明更改为

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

正如您在问题中指定的那样,您当然只接受 JSON 字符串。

关于java - Spring Cloud Stream 消息 JSON 转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002199/

相关文章:

java - 为什么将 ""附加到字符串可以节省内存?

java - 如何为 json 对象列表设置父级

java - SQL警告代码: 1364, SQLState:HY000字段 'district_code'没有默认值

json - 使用 serde 漂亮地打印没有换行符的 JSON?

apache-kafka - 使用 enable.idempotence true 时,Spring Cloud Stream Kafka 应用程序的启动速度极慢

kotlin - Spring Cloud Streams 的 StreamRetryTemplate 在集成测试中不重试

java - 处理 DATETIME 值 0000-00-00 00 :00:00 in JDBC

c# - 如何使用 Json.NET 反序列化可以是两种不同数据类型的 JSON 属性

javascript - jQuery json解码

java - Spring Cloud Stream 中使用 StreamBridge 的生产者回调