Service Activator 和.handle()方法

.handle()EIP 方法的目标是调用任何MessageHandlerimplementation 或任何方法。 另一种选择是使用 lambda 表达式定义 “活动”。 因此,我们引入了一个泛型GenericHandler<P>functional 接口。 其handlemethod 需要两个参数:P payloadMessageHeaders headers(从版本 5.1 开始)。 有了这个,我们可以定义一个 flow,如下所示:spring-doc.cadn.net.cn

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

前面的示例将它接收的任何整数加倍。spring-doc.cadn.net.cn

但是,Spring 集成的一个主要目标是loose coupling,通过从消息负载到消息处理程序的目标参数的运行时类型转换。 由于 Java 不支持 lambda 类的泛型类型解析,因此我们引入了一种解决方法,即payloadType参数,以及LambdaMessageProcessor. 这样做会将硬转换工作委托给 Spring 的ConversionService,它使用提供的type以及请求的 message 到 target 方法参数。 以下示例显示了生成的IntegrationFlow可能看起来像:spring-doc.cadn.net.cn

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

我们也可以注册一些BytesToIntegerConverterConversionService去掉那个额外的.transform():spring-doc.cadn.net.cn

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

@Bean
public IntegrationFlow integerFlow() {
    return IntegrationFlow.from("input")
             .handle(Integer.class, (p, h) -> p * 2)
            .get();
}