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

Source Link

Document

Default constructor for convenient dependency injection via setters.

Usage

From source file:com.xoom.rabbit.test.Main.java

public static void main(String[] args) throws InterruptedException {
    if (args.length != 9) {
        System.out.println(//from w w w  .  j  a v  a 2 s.  c  o  m
                "usage: java -jar target/rabbit-tester-0.1-SNAPSHOT-standalone.jar [consumer_threads] [number_of_messages] [amqp_host] [amqp_port] [produce] [consume] [message size in bytes] [username] [password]");
        return;
    }
    final long startTime = System.currentTimeMillis();
    int consumerThreads = Integer.parseInt(args[0]);
    final int messages = Integer.parseInt(args[1]);
    String host = args[2];
    int port = Integer.parseInt(args[3]);
    boolean produce = Boolean.parseBoolean(args[4]);
    boolean consume = Boolean.parseBoolean(args[5]);
    final int messageSize = Integer.parseInt(args[6]);
    String username = args[7];
    String password = args[8];

    if (produce) {
        System.out.println("Sending " + messages + " messages to " + host + ":" + port);
    }
    if (consume) {
        System.out.println("Consuming " + messages + " messages from " + host + ":" + port);
    }
    if (!produce && !consume) {
        System.out.println("Not producing or consuming any messages.");
    }

    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setChannelCacheSize(consumerThreads + 1);

    RabbitAdmin amqpAdmin = new RabbitAdmin(connectionFactory);

    DirectExchange exchange = new DirectExchange(EXCHANGE_NAME, true, false);
    Queue queue = new Queue(QUEUE_NAME);
    amqpAdmin.declareExchange(exchange);
    amqpAdmin.declareQueue(queue);
    amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY));

    final AmqpTemplate amqpTemplate = new RabbitTemplate(connectionFactory);

    final CountDownLatch producerLatch = new CountDownLatch(messages);
    final CountDownLatch consumerLatch = new CountDownLatch(messages);

    SimpleMessageListenerContainer listenerContainer = null;

    if (consume) {
        listenerContainer = new SimpleMessageListenerContainer();
        listenerContainer.setConnectionFactory(connectionFactory);
        listenerContainer.setQueueNames(QUEUE_NAME);
        listenerContainer.setConcurrentConsumers(consumerThreads);
        listenerContainer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (consumerLatch.getCount() == 1) {
                    System.out.println("Finished consuming " + messages + " messages in "
                            + (System.currentTimeMillis() - startTime) + "ms");
                }
                consumerLatch.countDown();
            }
        });
        listenerContainer.start();
    }

    if (produce) {
        while (producerLatch.getCount() > 0) {
            try {
                byte[] message = new byte[messageSize];
                RND.nextBytes(message);
                amqpTemplate.send(EXCHANGE_NAME, ROUTING_KEY, new Message(message, new MessageProperties()));
                producerLatch.countDown();
            } catch (Exception e) {
                System.out.println("Failed to send message " + (messages - producerLatch.getCount())
                        + " will retry forever.");
            }
        }
    }

    if (consume) {
        consumerLatch.await();
        listenerContainer.shutdown();
    }

    connectionFactory.destroy();
}

From source file:com.anton.dev.tqrbs2.QueueConsumeProcess.java

private void consume() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames("test.queue.1", "test.queue.2", "test.queue.3", "test.queue.4", "test.queue.5");
    container.setMessageListener(new MessageListenerAdapter(this));
    container.start();// w  w  w .j  a  v a2s .  c  o  m
}

From source file:com.vcredit.lrh.backend.RabbitConfiguration.java

@Bean
public SimpleMessageListenerContainer appLogContainer(ConnectionFactory connectionFactory) {

    if (!StringUtils.isEmpty(rabbitMQProperties.getLogQueue())) {
        MessageListenerAdapter listener = new MessageListenerAdapter(aPPLogMessageReceiver, "receiveMessage");
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(rabbitMQProperties.getLogQueue());
        container.setMessageListener(listener);
        return container;
    } else {/*from  w  ww  .  j  ava  2  s .com*/
        return null;
    }

}

From source file:de.msg.message.amqp.AmqpConfiguration.java

@Bean
public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
        MessageListenerAdapter listenerAdapter, MessageConverter jsonMessageConverter) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(QUEUE_NAME);
    container.setMessageConverter(jsonMessageConverter);
    container.setMessageListener(listenerAdapter);
    return container;
}

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  a va  2 s  .  c  om

    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:com.vcredit.lrh.backend.RabbitConfiguration.java

@Bean
public SimpleMessageListenerContainer scheduleTaskContainer(ConnectionFactory connectionFactory) {
    if (!StringUtils.isEmpty(rabbitMQProperties.getScheduleTaskQueue())) {
        MessageListenerAdapter listener1 = new MessageListenerAdapter(scheduleTaskMessageReceiver,
                "receiveMessage");
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(rabbitMQProperties.getScheduleTaskQueue());
        container.setMessageListener(listener1);
        return container;
    } else {/*  w  ww. ja v a 2  s. c  om*/
        return null;
    }
}

From source file:vn.topmedia.monitor.rabbit.client.RabbitClientConfiguration.java

@Bean
public SimpleMessageListenerContainer listenerContainer() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory());
    container.setQueues(marketDataQueue());
    container.setMessageListener(messageListenerAdapter());
    return container;
}

From source file:be.rufer.playground.amqpclient.config.RabbitConfig.java

@Bean
public SimpleMessageListenerContainer listenerContainer() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory());
    container.setQueueNames(this.queueName);
    container.setMessageListener(createMessageListenerAdapter());
    return container;
}

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   ww w.  ja v  a  2 s. c  o m
    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:lab.example.service.MessageListener.java

@Bean
SimpleMessageListenerContainer listenerContainer(ConnectionFactory connectionFactory,
        MessageListenerAdapter listenerAdapter) {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.setQueueNames(personEventsQueueName);
    container.setMessageListener(listenerAdapter);

    return container;
}