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: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 ww  w. j  a va2s. 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);/*  www . j  a va 2s .  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:limey.git.amqp.SampleAmqpSimpleApplication.java

@Bean
public SimpleMessageListenerContainer container() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    Object listener = new Object() {
        @SuppressWarnings("unused")
        public void handleMessage(String foo) {
            System.out.println(foo);
        }//from   w  w w .  j  a  v a  2  s  .c o  m
    };
    MessageListenerAdapter adapter = new MessageListenerAdapter(listener);
    container.setMessageListener(adapter);
    container.setQueueNames("foo");
    return container;
}

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());/* w w  w.ja va 2s  .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:org.farrukh.examples.amqp.Application.java

/**
 * Simple message listener container//from  w  w w .jav a2  s . co  m
 * @param connectionFactory - RabbitMQ connection factory.
 * @param configuration - Custom application information.
 * @param messageListener - The message listener with delegate object in the adapter.
 * @return
 */
@Bean
public SimpleMessageListenerContainer messageListenerContainer(final ConnectionFactory connectionFactory,
        final ApplicationProperties configuration, final MessageListener messageListener) {
    SimpleMessageListenerContainer messageListenerContainer = new SimpleMessageListenerContainer(
            connectionFactory);
    messageListenerContainer.addQueueNames(configuration.getQueueName());
    messageListenerContainer.setMessageListener(messageListener);
    return messageListenerContainer;
}

From source file:io.acme.solution.api.test.conf.RabbitTestConfigurer.java

@Bean
public SimpleMessageListenerContainer getMessageListenerContainer(final ConnectionFactory connectionFactory,
        final Queue commandDrainQueue, final MessageListenerAdapter messageListener) {

    final SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
    container.setQueues(commandDrainQueue);
    container.setMessageListener(messageListener);

    return container;
}

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

/**
 * Tie a Groovy closure to a message callback.
 *
 * @param args/*from   w  w w. j av  a2 s  . c o m*/
 * @return The BlockingQueue to poll for results
 */
@Override
public Object call(Object[] args) {
    final Closure callback = (args.length > 0 && args[0] instanceof Closure ? (Closure) args[0] : null);
    if (null == callback) {
        throw new IllegalStateException(
                "You must provide a callback to listen() (otherwise, what's the point?)");
    }
    Queue replyQueue = rabbitAdmin.declareQueue();
    listener = new SimpleMessageListenerContainer(connectionFactory);
    listener.setQueues(replyQueue);
    final Listener helper = new Listener(replyQueue.getName());
    listener.setMessageListener(new MessageListener() {
        public void onMessage(Message message) {
            byte[] body = message.getBody();
            try {
                Object obj = mapper.readValue(body, 0, body.length, Map.class);
                helper.getResultsQueue()
                        .add(callback.call(new Object[] { obj, message.getMessageProperties() }));
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            if ("end".equals(message.getMessageProperties().getType())) {
                helper.getResultsQueue().add(false);
            }
        }
    });
    listener.start();

    return helper;
}

From source file:io.acme.solution.query.conf.EventBusConfigurer.java

@PostConstruct
private void setup() {

    Queue currentQueue = null;/*w  w  w .j  av a  2  s .c  om*/
    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:com.jbrisbin.vpc.jobsched.mapred.MapReduceMessageHandler.java

public void start() {
    phase = STARTING;/*www . j a  v a 2  s.com*/
    controlQueue = rabbitAdmin.declareQueue();
    FanoutExchange x = new FanoutExchange(mapreduceControlExchange);
    rabbitAdmin.declareExchange(x);
    rabbitAdmin.declareBinding(new Binding(controlQueue, x));

    listeners = new SimpleMessageListenerContainer(connectionFactory);
    listeners.setMessageListener(new MapReduceControlHandler());
    listeners.setQueues(controlQueue);
    listeners.start();

    phase = STARTED;
}

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

@PostConstruct
private void setup() {

    Queue currentQueue = null;//from ww  w  .j  ava 2  s .com
    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();
        }
    }

}