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

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

Introduction

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

Prototype

@Override
public void start() 

Source Link

Document

Start this container.

Usage

From source file:com.mtech.easyexchange.ordersolver.OrderSolverConfigurer.java

public static void main(String... args) throws Exception {

    ConnectionFactory cf = new CachingConnectionFactory("127.0.0.1");

    RabbitAdmin admin = new RabbitAdmin(cf);

    Queue queue = new Queue("OrderQueue");
    admin.declareQueue(queue);//from  w  w  w . j a v a2s . c o m

    TopicExchange exchange = new TopicExchange("OrderExchange");
    admin.declareExchange(exchange);

    admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("*"));

    OrderMessageHolder holder = new OrderMessageHolder();

    OrderSolverThread ost = new OrderSolverThread(holder);
    ost.start();

    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf);
    container.setMessageListener(new OrderMessageConsumer(holder));
    container.setQueueNames("OrderQueue");
    container.start();
}

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);//w w w  .  j av  a2s  . c  om
    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: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  a2 s.c om
                "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();
}

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);// www  .  j  a va 2 s  .co 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:com.jbrisbin.vpc.jobsched.batch.BatchMessageHandler.java

public BatchMessage handleMessage(BatchMessage batch) throws Exception {
    log.debug("handling message: " + batch.toString());

    final BatchMessage results = new BatchMessage();
    results.setId(batch.getId());//from  w ww.  ja  va  2 s . com

    // For waiting till our results are all back
    final CountDownLatch latch = new CountDownLatch(batch.getMessages().size());

    Queue resultsQueue = rabbitAdmin.declareQueue();
    SimpleMessageListenerContainer listener = new SimpleMessageListenerContainer(connectionFactory);
    listener.setAutoAck(true);
    listener.setQueues(resultsQueue);
    listener.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            String messageId = new String(message.getMessageProperties().getCorrelationId());
            String body = new String(message.getBody());
            results.getMessages().put(messageId, body);
            latch.countDown();
        }
    });
    listener.start();

    for (Map.Entry<String, String> msg : batch.getMessages().entrySet()) {
        final String[] parts = msg.getKey().split(":");
        template.send(parts[0], parts[1],
                new MessageCreator(parts[2], parts[3], resultsQueue.getName(), msg.getValue().getBytes()));
    }

    // Wait the timeout value per message for all results to be collected
    latch.await((batch.getTimeout() * batch.getMessages().size()), TimeUnit.MINUTES);

    return results;
}

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

@Override
public void handleZorbaRequest(ZorbaRequest request) throws MessagingException {
    if (request == null)
        return;//  w ww. j av 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:io.acme.solution.query.conf.EventBusConfigurer.java

@PostConstruct
private void setup() {

    Queue currentQueue = null;/*from ww w  .  ja va2  s.  com*/
    SimpleMessageListenerContainer currentContainer = null;
    MessageListenerAdapter currentAdapter = null;

    final RabbitAdmin rabbitAdmin = this.context.getBean("eventBusRabbitAdmin", RabbitAdmin.class);
    final ConnectionFactory connectionFactory = this.context.getBean("eventBusConnectionFactory",
            ConnectionFactory.class);
    final TopicExchange exchange = this.context.getBean("eventExchange", TopicExchange.class);
    final MessageConverter converter = this.context.getBean("eventBusMessageConverter", MessageConverter.class);
    final Map<String, EventHandler> eventHandlersRegistry = EventHandlerUtils
            .buildEventHandlersRegistry(this.handlerBasePackage, this.context);

    for (String eventType : eventHandlersRegistry.keySet()) {

        rabbitAdmin.declareQueue(currentQueue = new Queue(this.queuePrefix + eventType));
        rabbitAdmin.declareBinding(BindingBuilder.bind(currentQueue).to(exchange).with(eventType));

        currentAdapter = new MessageListenerAdapter(eventHandlersRegistry.get(eventType), converter);

        currentContainer = new SimpleMessageListenerContainer(connectionFactory);
        currentContainer.setMessageListener(currentAdapter);
        currentContainer.setQueues(currentQueue);
        currentContainer.start();
    }
}

From source file:io.acme.solution.application.conf.CommandBusConfigurer.java

@PostConstruct
private void setup() {

    Queue currentQueue = null;/*from  ww  w  .j av  a 2 s.co m*/
    String currentCommandType = null;
    SimpleMessageListenerContainer currentContainer = null;
    MessageListenerAdapter currentAdapter = null;

    final RabbitAdmin rabbitAdmin = this.context.getBean("commandBusRabbitAdmin", RabbitAdmin.class);
    final ConnectionFactory connectionFactory = this.context.getBean("commandBusConnectionFactory",
            ConnectionFactory.class);
    final TopicExchange exchange = this.context.getBean("commandExchange", TopicExchange.class);
    final MessageConverter converter = this.context.getBean("commandBusMessageConverter",
            MessageConverter.class);
    final Map<String, CommandHandler> commandHandlersRegistry = CommandHandlerUtils
            .buildCommandHandlersRegistry(this.handlerBasePackage, this.context);
    final ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AssignableTypeFilter(Command.class));

    for (BeanDefinition bean : scanner.findCandidateComponents(this.commandBasePackage)) {
        currentCommandType = bean.getBeanClassName().substring(bean.getBeanClassName().lastIndexOf('.') + 1);
        rabbitAdmin.declareQueue(currentQueue = new Queue(this.queuePrefix + currentCommandType));
        rabbitAdmin.declareBinding(BindingBuilder.bind(currentQueue).to(exchange).with(currentCommandType));

        if (commandHandlersRegistry.containsKey(bean.getBeanClassName())) {
            currentAdapter = new MessageListenerAdapter(commandHandlersRegistry.get(bean.getBeanClassName()),
                    converter);

            currentContainer = new SimpleMessageListenerContainer(connectionFactory);
            currentContainer.setMessageListener(currentAdapter);
            currentContainer.setQueues(currentQueue);
            currentContainer.start();
        }
    }

}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQBuilder.java

@Override
public Object invokeMethod(String methodName, Object args) {
    if (CONSUME.equals(methodName)) {
        Consume consume = new Consume();
        SimpleMessageListenerContainer listenerContainer = consume.getListenerContainer();
        Object[] params = (Object[]) args;
        for (Object param : params) {
            if (param instanceof Map) {
                Map paramMap = (Map) param;

                if (paramMap.containsKey(ON_MESSAGE)) {
                    Object onMessage = paramMap.get(ON_MESSAGE);
                    if (onMessage instanceof String) {
                        consume.setEventName((String) onMessage);
                    } else if (onMessage instanceof Closure) {
                        consume.setDelegate((Closure) onMessage);
                    } else if (onMessage instanceof MessageListener) {
                        listenerContainer.setMessageListener(onMessage);
                    } else {
                        listenerContainer.setMessageListener(new MessageListenerAdapter(onMessage));
                    }/*from w w  w .  jav  a 2s . c  o m*/
                }

                if (paramMap.containsKey(ACK)) {
                    AcknowledgeMode mode = AcknowledgeMode.valueOf(paramMap.get(ACK).toString().toUpperCase());
                    listenerContainer.setAcknowledgeMode(mode);
                } else {
                    listenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
                }

            } else if (param instanceof Closure) {
                consume.setDelegate((Closure) param);
            }
        }
        listenerContainer.setQueues(currentQueue);
        listenerContainer.afterPropertiesSet();
        listenerContainer.start();
        listenerContainers.add(listenerContainer);

        return super.invokeMethod(methodName, consume);
    } else if (PUBLISH.equals(methodName)) {
        Publish publish = new Publish();
        publish.invokeMethod(CALL, args);
        return super.invokeMethod(methodName, publish);
    }

    return super.invokeMethod(methodName, args);
}