Spring cloud - 输入与输出

问题描述 投票:0回答:1

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

我的问题:

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

From the docsINPUT用于获取数据,OUTPUT用于发送数据。为什么这个例子恰恰相反,如果我反过来,什么都没有?

java spring spring-cloud spring-cloud-stream
1个回答
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));
       }
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.