Search code examples
javaasynchronousspring-integrationgateway

Spring-Integration: QueueChannel


Short Summary:

I want to send messages to a queue and make multiple threads process this messages. The application should just send the messages asynchronously to a Gateway but should get blocked when the queue is full. Also I wanted to make the delivery to the Queue multi-threaded. My Problem is that my Queue would never block and take way more messages then its actual size is


Solution

  • I am not sure what you mean by "doesn't block". This works fine for me...

    @SpringBootApplication
    public class So46973604Application {
    
        private final Logger LOGGER = LoggerFactory.getLogger(So46973604Application.class);
    
        public static void main(String[] args) {
            SpringApplication.run(So46973604Application.class, args).close();
        }
    
        @Bean
        ApplicationRunner runner(Gate gate) {
            return args -> {
                for (int i = 0; i < 20; i++) {
                    gate.send("foo");
                    LOGGER.info("Sent " + i);
                }
            };
        }
    
        @Bean
        QueueChannel channel() {
            return new QueueChannel(10);
        }
    
        @ServiceActivator(inputChannel = "channel", poller = @Poller(fixedDelay = "0"))
        public void handle(String in) throws InterruptedException {
            Thread.sleep(1_000);
        }
    
        @MessagingGateway(defaultRequestChannel = "channel")
        public interface Gate {
    
            void send(String out);
    
        }
    
    }
    

    The first 10 are sent immediately, then one per second due to blocking waiting for queue space.

    Why do you feel you need an async gateway, if you want to block the caller?