服务激活器和 .handle() 方法

.handle() EIP 方法的目标是调用任何 MessageHandler 实现或某个 POJO 上的任何方法。另一个选项是使用 Lambda 表达式定义“活动”。因此,我们引入了一个通用的 GenericHandler<P> 函数式接口。它的 handle 方法需要两个参数:P payloadMessageHeaders headers(从版本 5.1 开始)。有了这些,我们可以定义一个流程,如下所示:

@Bean
public IntegrationFlow myFlow() {
    return IntegrationFlow.from("flow3Input")
        .<Integer>handle((p, h) -> p * 2)
        .get();
}

前面的示例将其收到的任何整数加倍。

然而,Spring Integration 的一个主要目标是“松耦合”,通过消息载荷到消息处理程序目标参数的运行时类型转换。由于 Java 不支持 Lambda 类的泛型类型解析,我们为大多数 EIP 方法和 LambdaMessageProcessor 引入了一个带有附加 payloadType 参数的变通方法。这样做将繁重的转换工作委托给 Spring 的 ConversionService,它使用提供的 type 和请求的消息来定位方法参数。下面的示例展示了生成的 IntegrationFlow 可能是什么样子:

@Bean
public IntegrationFlow integerFlow() {
    return IntegrationFlow.from("input")
            .<byte[], String>transform(p - > new String(p, "UTF-8"))
            .handle(Integer.class, (p, h) -> p * 2)
            .get();
}

我们还可以在 ConversionService 中注册一些 BytesToIntegerConverter 以摆脱额外的 .transform()

@Bean
@IntegrationConverter
public BytesToIntegerConverter bytesToIntegerConverter() {
   return new BytesToIntegerConverter();
}

@Bean
public IntegrationFlow integerFlow() {
    return IntegrationFlow.from("input")
             .handle(Integer.class, (p, h) -> p * 2)
            .get();
}
© . This site is unofficial and not affiliated with VMware.