【问题标题】:Spring cloud - Input vs OutputSpring cloud - 输入与输出
【发布时间】:2018-03-05 09:26:06
【问题描述】:

From this example:

@SpringBootApplication
@EnableBinding(MyProcessor.class)
public class MultipleOutputsServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MultipleOutputsServiceApplication.class, args);
    }

    @Autowired
    private MyProcessor processor;

    @StreamListener(MyProcessor.INPUT)
    public void routeValues(Integer val) {
        if (val < 10) {
            processor.anOutput()
                .send(message(val));
        } else {
            processor.anotherOutput()
                .send(message(val));
        }
    }

    private static final <T> Message<T> message(T val) {
        return MessageBuilder.withPayload(val)
            .build();
    }
}

MyProcessor 接口:

public interface MyProcessor {
    String INPUT = "myInput";

    @Input
    SubscribableChannel myInput();

    @Output("myOutput")
    MessageChannel anOutput();

    @Output
    MessageChannel anotherOutput();
}

我的问题:

为什么MultipleOutputsServiceApplication类中的方法routeValues被注释为MyProcessor.INPUT而不是MyProcessor.myOutput(在将这个成员添加到MyProcessor接口之后)?

From the docs, INPUT 用于获取数据,OUTPUT 用于发送数据。为什么示例相反,如果我将其反转,则没有任何效果?

【问题讨论】:

    标签: java spring spring-cloud spring-cloud-stream


    【解决方案1】:

    这种方法对我来说是正确的。它不必使用@Output 进行注释,因为您的方法没有返回类型,并且您以编程方式将输出发送到方法中的任意目标(通过两个不同的输出绑定)。因此,您需要确保您的输出正确绑定,就像您的程序通过@EnableBinding(MyProcessor.class) 正确执行的那样。您需要方法上的@StreamListener(MyProcessor.INPUT),因为MyProcessor.INPUT 是StreamListener 正在侦听的绑定。一旦您通过该输入获取数据,您的代码就会以编程方式接管向下游发送数据。话虽如此,有多种方法可以解决这些类型的用例。您也可以这样做。

        @StreamListener
                    public void routeValues(@Input("input")SubscribableChannel input, 
        @Output("mOutput") MessageChannel myOutput, 
        @Output("output")MessageChannel output {
    
            input.subscribe(new MessageHandler() {
                            @Override
                            public void handleMessage(Message<?> message) throws MessagingException {
    
            int val = (int) message.getPayload();
    
            if (val < 10) {
                myOutput.send(message(val));
            } 
            else {
                output.send(message(val));
           }
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 2019-10-13
      • 1970-01-01
      • 2018-07-23
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多