Spring Integration在服务激活器中将有效负载转换为对象

时间:2018-07-26 14:41:17

标签: spring-integration

我正在关注此guide,以阅读来自Google Pub / Sub中某个主题的电子邮件通知。应用程序启动后,我会看到如下消息到达控制台:

Message arrived! Payload: {"emailAddress":"xxxxx@gmail.com","historyId":712315}

如何将有效负载转换为对象,以便可以检索emailAddress和historyId?

服务激活器如下:

@Bean
  @ServiceActivator(inputChannel = "pubsubInputChannel")
  public MessageHandler messageReceiver() {
    return message -> {
      LOGGER.info("Message arrived! Payload: " + message.getPayload());
      AckReplyConsumer consumer =
          (AckReplyConsumer) message.getHeaders().get(GcpPubSubHeaders.ACKNOWLEDGEMENT);
      consumer.ack();
    };
  }

我要将有效负载转换为的POJO对象是:

public class MessageNotification {

    private String emailAddress;

    private BigInteger historyId;

    public String getEmailAddress() {
        return emailAddress;
    }

    public BigInteger getHistoryId() {
        return historyId;
    }

    public void setHistoryId(BigInteger historyId) {
        this.historyId = historyId;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

2 个答案:

答案 0 :(得分:1)

看起来payload是JSON,因此您需要先使用Spring Integration Reference Manual并使用JsonToObjectTransformer,然后再使用该@ServiceActivator

@Bean
@Transformer(inputChannel = "pubsubInputChannel", outputChannel = "handleChannel")
public JsonToObjectTransformer jsonToObjectTransformer() {
    return new JsonToObjectTransformer(MessageNotification.class);
}

@Bean
@ServiceActivator(inputChannel = "handleChannel")
public MessageHandler messageReceiver() {

  ...

答案 1 :(得分:-1)

You can extract String message first: String jsonString =message.getPayload.toString();

Now you can convert this json string to:

ObjectMapper objectMapper = new ObjectMapper();
MessageNotification messageNotification = objectMapper.readValue(jsonString , MessageNotification.class);