Cherry
Cherry

Reputation: 33618

How await QueueChannel all message processed?

Consider a code:

@Configuration
public class MyConf {
      @MessagingGateway(defaultRequestChannel = "channel")
        public interface Sender {
            void send(String out);

        }

}

@Component
public class Consumer {
    @ServiceActivator(inputChannel = "channel", poller = @Poller(fixedRate = "100"))
    public void handle(String input) throws InterruptedException {
        //
    }
}

@Component
public class HistoricalTagRunner implements CommandLineRunner {
      @Autowired
      private Sender sender;

      @Override
      public void run(String... args) throws Exception {
            List<String> input = ...
            input.forEach(r -> sender.send(r));

            //ok, now all input is send and application exit
            //without waiting for message processing
      }
}

So all message are sent to consumer, but application exits without wating that all messages are processed Is there a way to tell spring wait until all messages in "channel" are processed?

Upvotes: 0

Views: 52

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121550

The Spring application is really just Java application and it is really not a Spring responsibility to control how your application is going to live. You can take into a service any Java feature to block a main thread until some event happens.

For example in our samples we use a System.in.read() to block main thread:

    System.out.println("Hit 'Enter' to terminate");
    System.in.read();
    ctx.close();

In this case end-user must enter something from the CLI to unblock that thread and exit from the program.

Another way is to wait for some CountDownLatch if you know a number of messages in advance. So, you flow must "count down" thast latch when a message is processed.

Upvotes: 1

Related Questions