服务激活器和 .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();
}