Example usage for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer SimpleMessageListenerContainer

List of usage examples for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer SimpleMessageListenerContainer

Introduction

In this page you can find the example usage for org.springframework.amqp.rabbit.listener SimpleMessageListenerContainer SimpleMessageListenerContainer.

Prototype

public SimpleMessageListenerContainer(ConnectionFactory connectionFactory) 

Source Link

Document

Create a listener container from the connection factory (mandatory).

Usage

From source file:io.spring.batch.configuration.JobConfiguration.java

@Bean
public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setQueueNames("partition.requests");
    container.setConcurrentConsumers(GRID_SIZE);

    return container;
}

From source file:com.jbrisbin.vpc.jobsched.mapred.MapReduceMessageHandler.java

private void listenForReReduce(MapReduceMessage msg) throws ScriptException, ResourceException {
    String hash = "rereduce." + DigestUtils.md5Hex(msg.getId());
    Queue q = new Queue(hash);
    q.setExclusive(true);/*from w  ww .  j  a  va 2  s  .  c  o m*/
    q.setDurable(false);
    q.setAutoDelete(true);
    rabbitAdmin.declareQueue(q);
    SimpleMessageListenerContainer c = new SimpleMessageListenerContainer(connectionFactory);
    c.setQueues(q);
    c.setMessageListener(new ReReduceListener(msg));
    c.start();
    listenerCache.put(hash, c);
}

From source file:org.resthub.rpc.AMQPHessianProxyFactory.java

/**
 * Initialize queues and the reply listener
 *//*  ww w  .  ja v  a  2  s  .c  o  m*/
private void initializeQueues() {
    if (!initializing.compareAndSet(false, true)) {
        return;
    }
    try {
        if (admin == null) {
            admin = new RabbitAdmin(connectionFactory);
        }
        this.createRequestQueue(admin, this.getRequestQueueName(this.serviceInterface),
                this.getRequestExchangeName(this.serviceInterface));
        if (replyQueueName == null) {
            replyQueueName = this.getReplyQueueName(this.serviceInterface);
        }
        Queue replyQueue = this.createReplyQueue(admin, replyQueueName);
        this.template.setReplyQueue(replyQueue);

        if (listener == null || !listener.isRunning()) {
            listener = new SimpleMessageListenerContainer(this.connectionFactory);
            listener.setMessageListener(this.template);
            listener.setQueues(replyQueue);
            listener.start();
        }
    } finally {
        initializing.compareAndSet(true, false);
    }
}

From source file:org.opentestsystem.delivery.logging.RabbitConfiguration.java

@Bean
public SimpleMessageListenerContainer listenerContainer(final ConnectionFactory connectionFactory,
        final Queue springCloudBus, final ConfigRefreshListener configRefreshListener) {
    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setQueues(springCloudBus);
    container.setMessageListener(configRefreshListener);
    return container;
}

From source file:org.springframework.amqp.rabbit.AsyncRabbitTemplate.java

/**
 * Construct an instance using the provided arguments. If 'replyAddress' is null,
 * replies will be routed to the default exchange using the reply queue name as the
 * routing key. Otherwise it should have the form exchange/routingKey and must
 * cause messages to be routed to the reply queue.
 * @param connectionFactory the connection factory.
 * @param exchange the default exchange to which requests will be sent.
 * @param routingKey the default routing key.
 * @param replyQueue the name of the reply queue to listen for replies.
 * @param replyAddress the reply address (exchange/routingKey).
 *//*from w w  w .j a va 2  s  .  co  m*/
public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey,
        String replyQueue, String replyAddress) {
    Assert.notNull(connectionFactory, "'connectionFactory' cannot be null");
    Assert.notNull(routingKey, "'routingKey' cannot be null");
    Assert.notNull(replyQueue, "'replyQueue' cannot be null");
    this.template = new RabbitTemplate(connectionFactory);
    this.template.setExchange(exchange == null ? "" : exchange);
    this.template.setRoutingKey(routingKey);
    this.container = new SimpleMessageListenerContainer(connectionFactory);
    this.container.setQueueNames(replyQueue);
    this.container.setMessageListener(this);
    this.container.afterPropertiesSet();
    this.directReplyToContainer = null;
    if (replyAddress == null) {
        this.replyAddress = replyQueue;
    } else {
        this.replyAddress = replyAddress;
    }

}

From source file:org.springframework.amqp.rabbit.connection.LocalizedQueueConnectionFactoryTests.java

@SuppressWarnings("unchecked")
@Test//  www  .j  ava  2  s .c om
public void testFailOver() throws Exception {
    ConnectionFactory defaultConnectionFactory = mockCF("localhost:1234", null);
    String rabbit1 = "localhost:1235";
    String rabbit2 = "localhost:1236";
    String[] addresses = new String[] { rabbit1, rabbit2 };
    String[] adminUris = new String[] { "http://localhost:11235", "http://localhost:11236" };
    String[] nodes = new String[] { "rabbit@foo", "rabbit@bar" };
    String vhost = "/";
    String username = "guest";
    String password = "guest";
    final AtomicBoolean firstServer = new AtomicBoolean(true);
    final Client client1 = doCreateClient(adminUris[0], username, password, nodes[0]);
    final Client client2 = doCreateClient(adminUris[1], username, password, nodes[1]);
    final Map<String, ConnectionFactory> mockCFs = new HashMap<String, ConnectionFactory>();
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(1);
    mockCFs.put(rabbit1, mockCF(rabbit1, latch1));
    mockCFs.put(rabbit2, mockCF(rabbit2, latch2));
    LocalizedQueueConnectionFactory lqcf = new LocalizedQueueConnectionFactory(defaultConnectionFactory,
            addresses, adminUris, nodes, vhost, username, password, false, null) {

        @Override
        protected Client createClient(String adminUri, String username, String password)
                throws MalformedURLException, URISyntaxException {
            return firstServer.get() ? client1 : client2;
        }

        @Override
        protected ConnectionFactory createConnectionFactory(String address, String node) throws Exception {
            return mockCFs.get(address);
        }

    };
    Log logger = spy(TestUtils.getPropertyValue(lqcf, "logger", Log.class));
    doReturn(true).when(logger).isInfoEnabled();
    new DirectFieldAccessor(lqcf).setPropertyValue("logger", logger);
    doAnswer(new CallsRealMethods()).when(logger).debug(anyString());
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(lqcf);
    container.setQueueNames("q");
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    Channel channel = this.channels.get(rabbit1);
    assertNotNull(channel);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    verify(logger, atLeast(1)).info(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@foo at: localhost:1235"));

    // Fail rabbit1 and verify the container switches to rabbit2

    firstServer.set(false);
    this.consumers.get(rabbit1).handleCancel(consumerTags.get(rabbit1));
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    channel = this.channels.get(rabbit2);
    assertNotNull(channel);
    verify(channel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(), anyMap(),
            Matchers.any(Consumer.class));
    container.stop();
    verify(logger, atLeast(1)).info(captor.capture());
    assertTrue(assertLog(captor.getAllValues(), "Queue: q is on node: rabbit@bar at: localhost:1236"));
}

From source file:org.springframework.amqp.rabbit.core.AsyncRabbitTemplate.java

/**
 * Construct an instance using the provided arguments. If 'replyAddress' is null,
 * replies will be routed to the default exchange using the reply queue name as the
 * routing key. Otherwise it should have the form exchange/routingKey and must
 * cause messages to be routed to the reply queue.
 * @param connectionFactory the connection factory.
 * @param exchange the default exchange to which requests will be sent.
 * @param routingKey the default routing key.
 * @param replyQueue the name of the reply queue to listen for replies.
 * @param replyAddress the reply address (exchange/routingKey).
 *///w ww. j av  a 2  s .  c om
public AsyncRabbitTemplate(ConnectionFactory connectionFactory, String exchange, String routingKey,
        String replyQueue, String replyAddress) {
    Assert.notNull(connectionFactory, "'connectionFactory' cannot be null");
    Assert.notNull(routingKey, "'routingKey' cannot be null");
    Assert.notNull(replyQueue, "'replyQueue' cannot be null");
    this.template = new RabbitTemplate(connectionFactory);
    this.template.setExchange(exchange == null ? "" : exchange);
    this.template.setRoutingKey(routingKey);
    this.container = new SimpleMessageListenerContainer(connectionFactory);
    this.container.setQueueNames(replyQueue);
    this.container.setMessageListener(this);
    this.container.afterPropertiesSet();
    if (replyAddress == null) {
        this.replyAddress = replyQueue;
    } else {
        this.replyAddress = replyAddress;
    }

}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Test
public void testDebatchByContainer() throws Exception {
    final List<Message> received = new ArrayList<Message>();
    final CountDownLatch latch = new CountDownLatch(2);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    container.setQueueNames(ROUTE);//from w ww. j  a v  a  2 s .c o m
    container.setMessageListener((MessageListener) message -> {
        received.add(message);
        latch.countDown();
    });
    container.setReceiveTimeout(100);
    container.afterPropertiesSet();
    container.start();
    try {
        BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(2, Integer.MAX_VALUE, 30000);
        BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler);
        template.setConnectionFactory(this.connectionFactory);
        MessageProperties props = new MessageProperties();
        Message message = new Message("foo".getBytes(), props);
        template.send("", ROUTE, message);
        message = new Message("bar".getBytes(), props);
        template.send("", ROUTE, message);
        assertTrue(latch.await(10, TimeUnit.SECONDS));
        assertEquals(2, received.size());
        assertEquals("foo", new String(received.get(0).getBody()));
        assertEquals(3, received.get(0).getMessageProperties().getContentLength());
        assertEquals("bar", new String(received.get(1).getBody()));
        assertEquals(3, received.get(0).getMessageProperties().getContentLength());
    } finally {
        container.stop();
    }
}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Test
public void testDebatchByContainerPerformance() throws Exception {
    final List<Message> received = new ArrayList<Message>();
    int count = 100000;
    final CountDownLatch latch = new CountDownLatch(count);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    container.setQueueNames(ROUTE);/*w w w  .j a  v a 2  s .co  m*/
    container.setMessageListener((MessageListener) message -> {
        received.add(message);
        latch.countDown();
    });
    container.setReceiveTimeout(100);
    container.setPrefetchCount(1000);
    container.setTxSize(1000);
    container.afterPropertiesSet();
    container.start();
    try {
        BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(1000, Integer.MAX_VALUE, 30000);
        BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler);
        //         RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(this.connectionFactory);
        MessageProperties props = new MessageProperties();
        props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        Message message = new Message(new byte[256], props);
        StopWatch watch = new StopWatch();
        watch.start();
        for (int i = 0; i < count; i++) {
            template.send("", ROUTE, message);
        }
        assertTrue(latch.await(60, TimeUnit.SECONDS));
        watch.stop();
        // System .out .println(watch.getTotalTimeMillis());
        assertEquals(count, received.size());
    } finally {
        container.stop();
    }
}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Test
public void testDebatchByContainerBadMessageRejected() throws Exception {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    container.setQueueNames(ROUTE);/*from w  w  w .  j a v  a2  s. c  om*/
    container.setMessageListener((MessageListener) message -> {
    });
    container.setReceiveTimeout(100);
    ConditionalRejectingErrorHandler errorHandler = new ConditionalRejectingErrorHandler();
    container.setErrorHandler(errorHandler);
    container.afterPropertiesSet();
    container.start();
    Log logger = spy(TestUtils.getPropertyValue(errorHandler, "logger", Log.class));
    doReturn(true).when(logger).isWarnEnabled();
    doAnswer(new DoesNothing()).when(logger).warn(anyString(), any(Throwable.class));
    new DirectFieldAccessor(errorHandler).setPropertyValue("logger", logger);
    try {
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(this.connectionFactory);
        MessageProperties props = new MessageProperties();
        props.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT,
                MessageProperties.BATCH_FORMAT_LENGTH_HEADER4);
        Message message = new Message("\u0000\u0000\u0000\u0004foo".getBytes(), props);
        template.send("", ROUTE, message);
        Thread.sleep(1000);
        ArgumentCaptor<Object> arg1 = ArgumentCaptor.forClass(Object.class);
        ArgumentCaptor<Throwable> arg2 = ArgumentCaptor.forClass(Throwable.class);
        verify(logger).warn(arg1.capture(), arg2.capture());
        assertThat(arg2.getValue().getMessage(), containsString("Bad batched message received"));
    } finally {
        container.stop();
    }
}