Example usage for com.rabbitmq.client Channel basicConsume

List of usage examples for com.rabbitmq.client Channel basicConsume

Introduction

In this page you can find the example usage for com.rabbitmq.client Channel basicConsume.

Prototype

String basicConsume(String queue, Consumer callback) throws IOException;

Source Link

Document

Start a non-nolocal, non-exclusive consumer, with explicit acknowledgement and a server-generated consumerTag.

Usage

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostExecutor.java

License:Apache License

RabbitMQBifrostExecutor(Connection connection, ExecutorService executorService, int concurrency,
        ObjectMapper objectMapper, String requestQueue, String replyQueueName, long responseWaitTimeout)
        throws Exception {
    if (null == connection || null == connection.getConnection()) {
        throw new BifrostException(BifrostException.ErrorCode.INVALID_CONNECTION,
                "The provided connection is invalid. Call start() on connection to start it.");
    }//  ww w . j av a  2  s.c om
    this.executorService = executorService;
    this.objectMapper = objectMapper;
    this.requestQueue = requestQueue;
    this.replyQueueName = replyQueueName;
    this.publishChannel = connection.getConnection().createChannel();
    this.responseWaitTimeout = responseWaitTimeout;
    AMQP.Queue.DeclareOk requestQueueResponse = publishChannel.queueDeclare(requestQueue, true, false, false,
            Collections.<String, Object>singletonMap("x-ha-policy", "all"));
    AMQP.Queue.DeclareOk replyQueue = publishChannel.queueDeclare(replyQueueName, true, false, false,
            Collections.<String, Object>singletonMap("x-ha-policy", "all"));
    for (int i = 0; i < concurrency; i++) {
        Channel channel = connection.getConnection().createChannel();
        channel.basicQos(1);
        ReplyListener<T> listener = new ReplyListener<T>(channel, waiters, handlers, objectMapper);
        channel.basicConsume(replyQueueName, listener);
        listeners.add(listener);
    }
}

From source file:com.flipkart.bifrost.framework.impl.RabbitMQBifrostRemoteCallExecutionServer.java

License:Apache License

@Override
public void start() throws BifrostException {
    try {//ww  w. j ava2  s.c  o  m
        if (null == connection || null == connection.getConnection()) {
            throw new BifrostException(BifrostException.ErrorCode.INVALID_CONNECTION,
                    "The provided connection is invalid. Call start() on connection to start it.");
        }
        for (int i = 1; i <= concurrency; i++) {
            Channel channel = connection.getConnection().createChannel();
            RabbitMQExecutionServerListener<T> listener = new RabbitMQExecutionServerListener<T>(channel,
                    mapper);
            channel.basicQos(1);
            channel.basicConsume(requestQueue, listener);
            listeners.add(listener);
        }
    } catch (IOException e) {
        throw new BifrostException(BifrostException.ErrorCode.IO_ERROR, "Error registering listener", e);
    }
}

From source file:com.jbrisbin.vcloud.cache.RabbitMQAsyncCache.java

License:Apache License

@Override
public void start() {
    active.set(true);//from w w  w  . j a va2s.  c  om

    try {
        Channel channel = getConnection().createChannel();
        channel.exchangeDeclare(objectRequestExchange, "topic", true, false, null);
        channel.queueDeclare(id, true, false, true, null);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    // For loading objects
    for (int i = 0; i < maxWorkers; i++) {
        activeTasks.add(workerPool.submit(new ObjectSender()));
        activeTasks.add(workerPool.submit(new CommandSender()));
        workerPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Channel channel = getConnection().createChannel();
                    ObjectLoadMonitor loadMonitor = new ObjectLoadMonitor(channel);
                    channel.basicConsume(id, loadMonitor);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }

    activeTasks.add(workerPool.submit(new HeartbeatMonitor()));
    commandMessages.add(new CommandMessage("ping", heartbeatExchange, ""));
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (cacheNodes.size() > 0) {
                numOfCacheNodes.set(cacheNodes.size());
            }
        }
    }, 0, heartbeatInterval);
}

From source file:com.jbrisbin.vcloud.cache.RabbitMQAsyncCacheProvider.java

License:Apache License

@Override
public void start() {
    active.set(true);/*www . ja v  a 2 s.c om*/

    try {
        Channel channel = getConnection().createChannel();
        channel.exchangeDeclare(objectRequestExchange, "topic", true, false, null);
        channel.queueDeclare(cacheNodeQueueName, true, false, true, null);
        channel.queueBind(cacheNodeQueueName, objectRequestExchange, "#");
        channel.exchangeDeclare(heartbeatExchange, "fanout", true, false, null);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    activeTasks.add(workerPool.submit(new HeartbeatMonitor()));
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            commandMessages.add(new CommandMessage("ping", heartbeatExchange, ""));
        }
    }, 0, heartbeatInterval);
    delayTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            numOfPeers.set(peers.size());
            if (debug) {
                log.debug("Expecting responses from " + numOfPeers.get() + " peers.");
            }
        }
    }, heartbeatInterval, heartbeatInterval);

    for (int i = 0; i < maxWorkers; i++) {
        activeTasks.add(workerPool.submit(new ObjectSender()));
        activeTasks.add(workerPool.submit(new CommandSender()));
        workerPool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Channel channel = getConnection().createChannel();
                    ObjectMonitor monitor = new ObjectMonitor(channel);
                    channel.basicConsume(cacheNodeQueueName, monitor);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
    }
}

From source file:org.apache.airavata.gfac.monitor.impl.push.amqp.SimpleJobFinishConsumer.java

License:Apache License

public void listen() {
    try {/*from   ww w.ja  v  a2  s . co  m*/
        String queueName = ServerSettings.getSetting(Constants.GFAC_SERVER_PORT, "8950");
        String uri = "amqp://localhost";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setUri(uri);
        Connection conn = connFactory.newConnection();
        logger.info("--------Created the connection to Rabbitmq server successfully-------");

        final Channel ch = conn.createChannel();

        logger.info("--------Created the channel with Rabbitmq server successfully-------");

        ch.queueDeclare(queueName, false, false, false, null);

        logger.info("--------Declare the queue " + queueName + " in Rabbitmq server successfully-------");

        final QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        (new Thread() {
            public void run() {
                try {
                    while (true) {
                        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                        String message = new String(delivery.getBody());
                        logger.info(
                                "---------------- Job Finish message received:" + message + " --------------");
                        synchronized (completedJobsFromPush) {
                            completedJobsFromPush.add(message);
                        }
                        ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    }
                } catch (Exception ex) {
                    logger.error("--------Cannot connect to a RabbitMQ Server--------", ex);
                }
            }

        }).start();
    } catch (Exception ex) {
        logger.error("Cannot connect to a RabbitMQ Server: ", ex);
        logger.info("------------- Push monitoring for HPC jobs is disabled -------------");
    }
}

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

License:Apache License

@Test
public void testHardErrorAndReconnect() throws Exception {

    RabbitTemplate template = new RabbitTemplate(connectionFactory);
    RabbitAdmin admin = new RabbitAdmin(connectionFactory);
    Queue queue = new Queue("foo");
    admin.declareQueue(queue);/*from www . jav  a2s.c  om*/
    final String route = queue.getName();

    final CountDownLatch latch = new CountDownLatch(1);
    try {
        template.execute(new ChannelCallback<Object>() {
            @Override
            public Object doInRabbit(Channel channel) throws Exception {
                channel.getConnection().addShutdownListener(new ShutdownListener() {
                    @Override
                    public void shutdownCompleted(ShutdownSignalException cause) {
                        logger.info("Error", cause);
                        latch.countDown();
                        // This will be thrown on the Connection thread just before it dies, so basically ignored
                        throw new RuntimeException(cause);
                    }
                });
                String tag = channel.basicConsume(route, new DefaultConsumer(channel));
                // Consume twice with the same tag is a hard error (connection will be reset)
                String result = channel.basicConsume(route, false, tag, new DefaultConsumer(channel));
                fail("Expected IOException, got: " + result);
                return null;
            }
        });
        fail("Expected AmqpIOException");
    } catch (AmqpIOException e) {
        // expected
    }
    template.convertAndSend(route, "message");
    assertTrue(latch.await(1000, TimeUnit.MILLISECONDS));
    String result = (String) template.receiveAndConvert(route);
    assertEquals("message", result);
    result = (String) template.receiveAndConvert(route);
    assertEquals(null, result);
}

From source file:org.springframework.cloud.stream.binder.rabbit.RabbitBinderCleanerTests.java

License:Apache License

@Test
public void testCleanStream() {
    final RabbitBindingCleaner cleaner = new RabbitBindingCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;//w  w  w .ja v a  2s . c  om
    for (int i = 0; i < 5; i++) {
        String queue1Name = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX,
                BinderUtils.constructPipeName(stream1, i));
        String queue2Name = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX,
                BinderUtils.constructPipeName(stream2, i));
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", MessageChannelBinderSupport.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
    }
    CachingConnectionFactory connectionFactory = test.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    final FanoutExchange fanout1 = new FanoutExchange(MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX,
            MessageChannelBinderSupport.applyPubSub(BinderUtils.constructTapPrefix(stream1) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout1));
    final FanoutExchange fanout2 = new FanoutExchange(MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX,
            MessageChannelBinderSupport.applyPubSub(BinderUtils.constructTapPrefix(stream2) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout2));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = MessageChannelBinderSupport.applyPrefix(BINDER_PREFIX,
                    BinderUtils.constructPipeName(stream1, 4));
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertEquals("Queue " + queueName + " is in use", e.getMessage());
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e.getMessage(),
                        startsWith("Cannot delete exchange " + fanout1.getName() + "; it has bindings:"));
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertTrue("Consumer state remained at " + state + " after 10 seconds", n < 100);
        }

    });
    rabbitAdmin.deleteExchange(fanout1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(fanout1);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertEquals(2, cleanedMap.size());
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertEquals(10, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(BINDER_PREFIX + stream1 + "." + i, cleanedQueues.get(i * 2));
        assertEquals(BINDER_PREFIX + stream1 + "." + i + ".dlq", cleanedQueues.get(i * 2 + 1));
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout1.getName(), cleanedExchanges.get(0));

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertEquals(2, cleanedMap.size());
    cleanedQueues = cleanedMap.get("queues");
    assertEquals(5, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(BINDER_PREFIX + stream2 + "." + i, cleanedQueues.get(i));
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout2.getName(), cleanedExchanges.get(0));
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleanerTests.java

License:Apache License

@Test
public void testCleanStream() {
    final RabbitBusCleaner cleaner = new RabbitBusCleaner();
    final RestTemplate template = RabbitManagementUtils.buildRestTemplate("http://localhost:15672", "guest",
            "guest");
    final String stream1 = UUID.randomUUID().toString();
    String stream2 = stream1 + "-1";
    String firstQueue = null;/*from w  w  w.  ja v  a  2 s.  co m*/
    for (int i = 0; i < 5; i++) {
        String queue1Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.constructPipeName(stream1, i));
        String queue2Name = MessageBusSupport.applyPrefix(XDBUS_PREFIX, BusUtils.constructPipeName(stream2, i));
        if (firstQueue == null) {
            firstQueue = queue1Name;
        }
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue1Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queue2Name).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
        uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                .pathSegment("{vhost}", "{queue}")
                .buildAndExpand("/", MessageBusSupport.constructDLQName(queue1Name)).encode().toUri();
        template.put(uri, new AmqpQueue(false, true));
    }
    CachingConnectionFactory connectionFactory = test.getResource();
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    final FanoutExchange fanout1 = new FanoutExchange(MessageBusSupport.applyPrefix(XDBUS_PREFIX,
            MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(stream1) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout1);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout1));
    final FanoutExchange fanout2 = new FanoutExchange(MessageBusSupport.applyPrefix(XDBUS_PREFIX,
            MessageBusSupport.applyPubSub(BusUtils.constructTapPrefix(stream2) + ".foo.bar")));
    rabbitAdmin.declareExchange(fanout2);
    rabbitAdmin.declareBinding(BindingBuilder.bind(new Queue(firstQueue)).to(fanout2));
    new RabbitTemplate(connectionFactory).execute(new ChannelCallback<Void>() {

        @Override
        public Void doInRabbit(Channel channel) throws Exception {
            String queueName = MessageBusSupport.applyPrefix(XDBUS_PREFIX,
                    BusUtils.constructPipeName(stream1, 4));
            String consumerTag = channel.basicConsume(queueName, new DefaultConsumer(channel));
            try {
                waitForConsumerStateNot(queueName, 0);
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertEquals("Queue " + queueName + " is in use", e.getMessage());
            }
            channel.basicCancel(consumerTag);
            waitForConsumerStateNot(queueName, 1);
            try {
                cleaner.clean(stream1, false);
                fail("Expected exception");
            } catch (RabbitAdminException e) {
                assertThat(e.getMessage(),
                        startsWith("Cannot delete exchange " + fanout1.getName() + "; it has bindings:"));
            }
            return null;
        }

        private void waitForConsumerStateNot(String queueName, int state) throws InterruptedException {
            int n = 0;
            URI uri = UriComponentsBuilder.fromUriString("http://localhost:15672/api/queues")
                    .pathSegment("{vhost}", "{queue}").buildAndExpand("/", queueName).encode().toUri();
            while (n++ < 100) {
                @SuppressWarnings("unchecked")
                Map<String, Object> queueInfo = template.getForObject(uri, Map.class);
                if (!queueInfo.get("consumers").equals(Integer.valueOf(state))) {
                    break;
                }
                Thread.sleep(100);
            }
            assertTrue("Consumer state remained at " + state + " after 10 seconds", n < 100);
        }

    });
    rabbitAdmin.deleteExchange(fanout1.getName()); // easier than deleting the binding
    rabbitAdmin.declareExchange(fanout1);
    connectionFactory.destroy();
    Map<String, List<String>> cleanedMap = cleaner.clean(stream1, false);
    assertEquals(2, cleanedMap.size());
    List<String> cleanedQueues = cleanedMap.get("queues");
    // should *not* clean stream2
    assertEquals(10, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(XDBUS_PREFIX + stream1 + "." + i, cleanedQueues.get(i * 2));
        assertEquals(XDBUS_PREFIX + stream1 + "." + i + ".dlq", cleanedQueues.get(i * 2 + 1));
    }
    List<String> cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout1.getName(), cleanedExchanges.get(0));

    // wild card *should* clean stream2
    cleanedMap = cleaner.clean(stream1 + "*", false);
    assertEquals(2, cleanedMap.size());
    cleanedQueues = cleanedMap.get("queues");
    assertEquals(5, cleanedQueues.size());
    for (int i = 0; i < 5; i++) {
        assertEquals(XDBUS_PREFIX + stream2 + "." + i, cleanedQueues.get(i));
    }
    cleanedExchanges = cleanedMap.get("exchanges");
    assertEquals(1, cleanedExchanges.size());
    assertEquals(fanout2.getName(), cleanedExchanges.get(0));
}

From source file:org.teksme.server.queue.consumer.impl.ChannelTracker.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from   www  . ja v  a  2 s . c  o m
public Map<Channel, String> addingService(ServiceReference reference) {
    Connection conn = (Connection) context.getService(reference);
    String consumerTag = null;

    Map<Channel, String> registry = new HashMap<Channel, String>();
    Channel channel = null;
    try {

        XmlConfiguration read = new XmlConfiguration();

        TeksConfig.MessageMiddleware config = read.readMessageMiddlewareConfig("teks-server.xml");

        String queueName = null;

        List<MessageMiddleware.Queue> queues = config.getQueues();
        for (Queue queue : queues) {
            queueName = queue.getName();

            logger.info("Declaring basic MQ consumer for queue: " + queueName);

            channel = conn.createChannel();

            // ensure you never have more than 100 messages queued up in the
            // consumer
            channel.basicQos(100);

            Class consumerClazz;
            consumerClazz = Class.forName(queue.getConsumerClass());
            Constructor constructor = consumerClazz.getConstructor(Channel.class);

            BaseConsumer consumer = (BaseConsumer) constructor.newInstance(channel);

            // OutboundMessageConsumer consumer = new
            // OutboundMessageConsumer(channel);

            consumer.addMessageListener(new OutboundSMSHandler());
            consumerTag = channel.basicConsume(queueName, consumer);

            registry.put(channel, consumerTag);
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    return registry;
}

From source file:scratchpad.SimpleConsumer.java

License:Mozilla Public License

public static void main(String[] args) {
    try {//from   ww w.  j a va2s  . co  m
        String hostName = (args.length > 0) ? args[0] : "localhost";
        int portNumber = (args.length > 1) ? Integer.parseInt(args[1]) : AMQP.PROTOCOL.PORT;
        String queueName = (args.length > 2) ? args[2] : "eventName";

        ConnectionFactory connFactory = new ConnectionFactory();
        connFactory.setHost(hostName);
        connFactory.setPort(portNumber);
        Connection conn = connFactory.newConnection();

        final Channel ch = conn.createChannel();

        ch.queueDeclare();

        QueueingConsumer consumer = new QueueingConsumer(ch);
        ch.basicConsume(queueName, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            Envelope envelope = delivery.getEnvelope();
            System.out
                    .println("Routing Key: " + envelope.getRoutingKey() + ":" + new String(delivery.getBody()));
            ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    } catch (Exception ex) {
        System.err.println("Main thread caught exception: " + ex);
        ex.printStackTrace();
        System.exit(1);
    }
}