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

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

Introduction

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

Prototype

@Override
public void stop() 

Source Link

Document

Stop this container.

Usage

From source file:com.anton.dev.tqrbs2.basic.BasicJava.java

public static void main(String[] args) throws Exception {
    ConnectionFactory cf = new CachingConnectionFactory();

    // set up the queue, exchange, binding on the broker
    RabbitAdmin admin = new RabbitAdmin(cf);
    Queue queue = new Queue("myQueue");
    admin.declareQueue(queue);/*from www . ja v  a  2 s .co  m*/
    TopicExchange exchange = new TopicExchange("myExchange2");
    admin.declareExchange(exchange);
    admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("foo.*"));

    // set up the listener and container
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
    Object listener = new Object() {
        public void handleMessage(String foo) {
            LOGGER.info("Recibiendo Java: " + foo);
        }
    };
    MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
    container.setMessageListener(adapter);
    container.setQueueNames("myQueue");
    container.start();

    // send something
    RabbitTemplate template = new RabbitTemplate(cf);
    String msg = "Hello, world Rabbit!";
    LOGGER.info("Enviando Java: " + msg);
    template.convertAndSend("myExchange2", "foo.bar", msg);
    Thread.sleep(1000);
    container.stop();
}

From source file:org.carewebframework.amqp.rabbitmq.GlobalEventDispatcher.java

/**
 * Remove all remote subscriptions./*from ww w  . j  a va2 s . c om*/
 */
private void removeSubscriptions() {
    for (final SimpleMessageListenerContainer subscriber : this.subscribers.values()) {
        try {
            subscriber.stop();
        } catch (final Throwable e) {
            log.debug("Error closing subscriber", e);//is level appropriate - previously hidden exception -afranken
        }
    }

    this.subscribers.clear();
}

From source file:com.bbytes.zorba.messaging.rabbitmq.listener.impl.QueueNotificationHandler.java

@Override
public void handleZorbaRequest(ZorbaRequest request) throws MessagingException {
    if (request == null)
        return;/*from   w w w . j  av  a 2  s. c  om*/
    ZorbaData<String, Serializable> data = request.getData();
    if (data == null) {
        LOG.error("No data received along with request " + request.getId());
        return;
    }
    String queueName = (String) data.get("queueName");
    if (queueName == null || queueName.isEmpty()) {
        LOG.error("No Queue Name received along with request " + request.getId());
        return;
    }
    String event = (String) data.get("event");
    if (event.equals("CREATED")) {
        LOG.debug("New Queue Created. Adding Listener to that");
        final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setAutoStartup(false);
        container.setConnectionFactory(rabbitConnectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(
                new ZorbaRuntimeRequestHandlerImpl(jsonMessageConverter, zorbaRquestDelegationService));
        container.setConcurrentConsumers(3);
        queueListeners.put(queueName, container);
        // start the container
        Thread thread = new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                container.start();
            }
        };
        LOG.debug("Starting container for the queue " + queueName);
        thread.start();

    } else if (event.equals("DELETED")) {
        LOG.debug("Deleting container for the queue " + queueName);
        SimpleMessageListenerContainer container = queueListeners.get(queueName);
        if (container == null) {
            LOG.warn("SimpleMessageListenerContainer is null. Why?");
            return;
        }
        if (container.isRunning()) {
            container.stop();
        }
        container.destroy();
        queueListeners.remove(queueName);
    }

}

From source file:com.jbrisbin.vpc.jobsched.SubmitClosure.java

@Override
public Object call(Object[] args) {
    log.debug("args: " + args);
    String exch = args[0].toString();
    String route = args[1].toString();
    final Object body = args[2];
    Map headers = null;/*from   w  w  w.  j  av  a 2  s .  c  o  m*/

    final BlockingQueue<Object> resultsQueue = new LinkedBlockingQueue<Object>();
    Queue replyQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer();
    listener.setQueues(replyQueue);
    if (args.length > 3) {
        for (int i = 3; i <= args.length; i++) {
            if (args[i] instanceof MessageListener) {
                MessageListener callback = (MessageListener) args[3];
                listener.setMessageListener(callback);
            } else if (args[i] instanceof Map) {
                headers = (Map) args[i];
            }
        }
    } else {
        listener.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                byte[] body = message.getBody();
                try {
                    resultsQueue.add(mapper.readValue(body, 0, body.length, Map.class));
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    final Map msgHdrs = headers;
    rabbitTemplate.send(exch, route, new MessageCreator() {
        public Message createMessage() {
            MessageProperties props = new RabbitMessageProperties();
            props.setContentType("application/json");
            if (null != msgHdrs) {
                props.getHeaders().putAll(msgHdrs);
            }
            String uuid = UUID.randomUUID().toString();
            props.setCorrelationId(uuid.getBytes());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                mapper.writeValue(out, body);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            Message msg = new Message(out.toByteArray(), props);
            return msg;
        }
    });

    Object results = null;
    try {
        results = resultsQueue.poll(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    }
    listener.stop();

    return results;
}

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

@SuppressWarnings("unchecked")
@Test/*ww w. j a v  a2  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.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  w  w.j  a va  2s  .com*/
    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);/*from w  w w. java2 s  . c  om*/
    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  . ja  v a  2 s.co m
    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();
    }
}

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

@Test
public void testCompressionWithContainer() 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 www. j av a2 s .c om
    container.setMessageListener((MessageListener) message -> {
        received.add(message);
        latch.countDown();
    });
    container.setReceiveTimeout(100);
    container.setAfterReceivePostProcessors(new DelegatingDecompressingPostProcessor());
    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);
        template.setBeforePublishPostProcessors(new GZipPostProcessor());
        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.RabbitTemplatePublisherCallbacksIntegrationTests.java

@Test
public void testPublisherConfirmWithSendAndReceive() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<CorrelationData> confirmCD = new AtomicReference<CorrelationData>();
    templateWithConfirmsEnabled.setConfirmCallback((correlationData, ack, cause) -> {
        confirmCD.set(correlationData);//from w  w w .  j a  v  a 2s.  c  om
        latch.countDown();
    });
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(
            this.connectionFactoryWithConfirmsEnabled);
    container.setQueueNames(ROUTE);
    container.setMessageListener(
            new MessageListenerAdapter((ReplyingMessageListener<String, String>) String::toUpperCase));
    container.start();
    CorrelationData correlationData = new CorrelationData("abc");
    String result = (String) this.templateWithConfirmsEnabled.convertSendAndReceive(ROUTE, (Object) "message",
            correlationData);
    container.stop();
    assertEquals("MESSAGE", result);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertEquals(correlationData, confirmCD.get());
}