List of usage examples for com.rabbitmq.client Channel basicConsume
String basicConsume(String queue, boolean autoAck, Consumer callback) throws IOException;
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test/*from ww w. j a v a 2s .co m*/ public void testConnect$shouldCleanUpOnConsumerRegistrationFailure(@Mocked final Channel channel, @Mocked final Queue.DeclareOk ok) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1) void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } }; final CollectorConfiguration defaultCollector = defaultCollector(); new Expectations() { { channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any); this.result = ok; ok.getQueue(); this.result = "actualQueueName"; channel.basicConsume("actualQueueName", false, (Consumer) this.any); this.result = new IOException("Failure"); } }; final CollectorController sut = collectorController(defaultCollector); try { sut.connect(); fail("Should not connect on failure"); } catch (final ControllerException e) { assertThat(e.getMessage(), equalTo("Could not register consumer for queue 'actualQueueName'")); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } }
From source file:org.smartdeveloperhub.harvesters.it.notification.CollectorControllerTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test/* w w w . jav a 2s . c om*/ public void testDisconnect$ignoreCleanerFailures(@Mocked final Channel channel, @Mocked final Queue.DeclareOk ok) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1) void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } }; final CollectorConfiguration defaultCollector = defaultCollector(); final CollectorController sut = collectorController(defaultCollector); new Expectations() { { channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any); this.result = ok; ok.getQueue(); this.result = "actualQueueName"; channel.basicConsume("actualQueueName", false, (Consumer) this.any); channel.queueUnbind("actualQueueName", defaultCollector.getExchangeName(), (String) this.any); this.result = new IOException("failure"); } }; sut.connect(); sut.disconnect(); }
From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test/* w w w . j av a 2s. c om*/ public void testConnect$shouldCleanUpOnConsumerRegistrationFailure(@Mocked final Channel channel, @Mocked final Queue.DeclareOk ok) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1) void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } }; final Collector defaultCollector = defaultCollector(); new Expectations() { { channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any); this.result = ok; ok.getQueue(); this.result = "actualQueueName"; channel.basicConsume("actualQueueName", false, (Consumer) this.any); this.result = new IOException("Failure"); } }; final CollectorController sut = collectorController(defaultCollector); try { sut.connect(); fail("Should not connect on failure"); } catch (final ControllerException e) { assertThat(e.getMessage(), equalTo("Could not register consumer for queue 'actualQueueName'")); assertThat(e.getCause(), instanceOf(IOException.class)); assertThat(e.getCause().getMessage(), equalTo("Failure")); } }
From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java
License:Apache License
@SuppressWarnings("unchecked") @Test/*from www. j a v a 2s. co m*/ public void testDisconnect$ignoreCleanerFailures(@Mocked final Channel channel, @Mocked final Queue.DeclareOk ok) throws Exception { new MockUp<ConnectionManager>() { private boolean connected = false; @Mock(invocations = 1) void connect() { this.connected = true; } @Mock(invocations = 1) void disconnect() { } @Mock boolean isConnected() { return this.connected; } @Mock Channel channel() { return channel; } }; final Collector defaultCollector = defaultCollector(); final CollectorController sut = collectorController(defaultCollector); new Expectations() { { channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any); this.result = ok; ok.getQueue(); this.result = "actualQueueName"; channel.basicConsume("actualQueueName", false, (Consumer) this.any); channel.queueUnbind("actualQueueName", defaultCollector.getExchangeName(), (String) this.any); this.result = new IOException("failure"); } }; sut.connect(); sut.disconnect(); }
From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java
License:Apache License
@Test public void testProperties() throws Exception { SingleConnectionFactory connectionFactory = new SingleConnectionFactory(); connectionFactory.setHost("localhost"); RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); String queueName = "test.properties." + System.currentTimeMillis(); try {//from w w w. ja v a 2s . c o m rabbitAdmin.declareQueue(new Queue(queueName)); new RabbitTemplate(connectionFactory).convertAndSend(queueName, "foo"); int n = 0; while (n++ < 100 && messageCount(rabbitAdmin, queueName) == 0) { Thread.sleep(100); } assertTrue("Message count = 0", n < 100); Channel channel = connectionFactory.createConnection().createChannel(false); DefaultConsumer consumer = new DefaultConsumer(channel); channel.basicConsume(queueName, true, consumer); n = 0; while (n++ < 100 && messageCount(rabbitAdmin, queueName) > 0) { Thread.sleep(100); } assertTrue("Message count > 0", n < 100); Properties props = rabbitAdmin.getQueueProperties(queueName); assertNotNull(props.get(RabbitAdmin.QUEUE_CONSUMER_COUNT)); assertEquals(1, props.get(RabbitAdmin.QUEUE_CONSUMER_COUNT)); channel.close(); } finally { rabbitAdmin.deleteQueue(queueName); connectionFactory.destroy(); } }
From source file:org.springframework.amqp.rabbit.MulticastMain.java
License:Mozilla Public License
public static void main(String[] args) { Options options = getOptions();/*w w w . ja v a2 s . c om*/ CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String hostName = strArg(cmd, 'h', "localhost"); int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT); String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int messageCount = intArg(cmd, 'N', 0); int consumerCount = intArg(cmd, 'y', 1); int connectionCount = cmd.hasOption('c') ? 1 : consumerCount; int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<String> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); // setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(hostName); factory.setPort(portNumber); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Connection[] consumerConnections = new Connection[connectionCount]; for (int i = 0; i < connectionCount; i++) { Connection conn = factory.newConnection(); consumerConnections[i] = conn; } Thread[] consumerThreads = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = consumerConnections[i % connectionCount]; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null) .getQueue(); QueueingConsumer consumer = new QueueingConsumer(channel); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.basicConsume(queueName, autoAck, consumer); channel.queueBind(queueName, exchangeName, id); Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); if (producerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount); channel.addReturnListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); } for (int i = 0; i < connectionCount; i++) { consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:org.thingsboard.server.extensions.rabbitmq.DemoClient.java
License:Apache License
public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST);//from www . j a v a 2 s .c o m factory.setUsername(USERNAME); factory.setPassword(PASSWORD); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages."); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); }
From source file:org.voltdb.bulkloader.RMQCSVReceive.java
License:Open Source License
public static void receiveMessages(RMQOptions rmqOpts, TestOptions testOpts, String[] args) throws IOException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(rmqOpts.host);/*www . j av a 2s. co m*/ Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); if (rmqOpts.exchange != null) { if (rmqOpts.extype != null) { channel.exchangeDeclare(rmqOpts.exchange, rmqOpts.extype); } for (String bindingKey : rmqOpts.bindings) { channel.queueBind(rmqOpts.queue, rmqOpts.exchange, bindingKey); } } try { channel.queueDeclare(rmqOpts.queue, rmqOpts.persistent, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); channel.basicQos(1); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(rmqOpts.queue, false, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // Sleep 1 second for every trailing '.'. int dotCount = 0; for (int i = message.length() - 1; i >= 0; --i) { if (message.charAt(i) == '.') { dotCount++; } else { break; } } if (dotCount > 0) { message = message.substring(0, message.length() - dotCount); } System.out.printf(" [x] Received '%s'\n", message); Thread.sleep(dotCount * 1000); } } catch (ShutdownSignalException | ConsumerCancelledException | InterruptedException e) { e.printStackTrace(); } finally { channel.close(); connection.close(); } }
From source file:org.wildfly.connector.rabbitmq.ConnectorTestCase.java
License:Open Source License
@Test public void testConnectionFactory() throws Exception { Assert.assertNotNull(connectionFactory1); Assert.assertNotNull(queue);//w w w .j av a 2 s . co m RabbitmqConnection connection = connectionFactory1.getConnection(); Assert.assertNotNull(connection); String queueName = "testing"; Channel channel = connection.createChannel(); channel.queueDeclare(queueName, false, false, false, null); String message = "Hello World!"; final CountDownLatch counter = new CountDownLatch(1); Consumer consume = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { Assert.assertEquals("Hello World!", new String(body)); counter.countDown(); } }; channel.basicConsume(queueName, true, consume); channel.basicPublish("", queueName, null, message.getBytes()); counter.await(10, TimeUnit.SECONDS); Assert.assertEquals(0, counter.getCount()); channel.close(); }
From source file:org.wso2.carbon.caching.invalidator.amqp.CacheInvalidationSubscriber.java
License:Open Source License
private void subscribe() { log.debug("Global cache invalidation: initializing the subscription"); try {/*from www .jav a 2 s . co m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(ConfigurationManager.getProviderUrl()); int port = Integer.parseInt(ConfigurationManager.getProviderPort()); factory.setPort(port); factory.setUsername(ConfigurationManager.getProviderUsername()); factory.setPassword(ConfigurationManager.getProviderPassword()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.exchangeDeclare(ConfigurationManager.getTopicName(), "topic"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, ConfigurationManager.getTopicName(), "#"); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); Thread reciever = new Thread(messageReciever); reciever.start(); log.info("Global cache invalidation is online"); } catch (Exception e) { log.error("Global cache invalidation: Error message broker initialization", e); } }