List of usage examples for com.rabbitmq.client Channel close
@Override void close() throws IOException, TimeoutException;
From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java
License:Apache License
private void closeResources(Connection connection, Channel channel) { if (channel != null) { try {//ww w . j ava2 s . c o m channel.close(); } catch (IOException | TimeoutException e) { // Ignore } } if (connection != null) { try { connection.close(); } catch (IOException e) { // Ignore } } }
From source file:org.springframework.amqp.rabbit.junit.RabbitAvailableCTORInjectionTests.java
License:Apache License
@Test public void test(ConnectionFactory cf) throws Exception { assertSame(cf, this.connectionFactory); Connection conn = this.connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close(); conn.close();/*from www . j a v a 2 s . com*/ }
From source file:org.springframework.amqp.rabbit.junit.RabbitAvailableTests.java
License:Apache License
@Test public void test(ConnectionFactory connectionFactory) throws Exception { Connection conn = connectionFactory.newConnection(); Channel channel = conn.createChannel(); DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue"); assertEquals(0, declareOk.getConsumerCount()); channel.close(); conn.close();/*from w w w .j ava2 s . co m*/ }
From source file:org.springframework.amqp.rabbit.listener.BlockingQueueConsumer.java
License:Apache License
private void checkMissingQueues() { long now = System.currentTimeMillis(); if (now - this.retryDeclarationInterval > this.lastRetryDeclaration) { synchronized (this.missingQueues) { Iterator<String> iterator = this.missingQueues.iterator(); while (iterator.hasNext()) { boolean available = true; String queue = iterator.next(); Channel channel = null; try { channel = this.connectionFactory.createConnection().createChannel(false); channel.queueDeclarePassive(queue); if (logger.isInfoEnabled()) { logger.info("Queue '" + queue + "' is now available"); }//from w w w. j ava 2 s . c o m } catch (IOException e) { available = false; if (logger.isWarnEnabled()) { logger.warn("Queue '" + queue + "' is still not available"); } } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { //Ignore it } } } if (available) { try { this.consumeFromQueue(queue); iterator.remove(); } catch (IOException e) { throw RabbitExceptionTranslator.convertRabbitAccessException(e); } } } } this.lastRetryDeclaration = now; } }
From source file:org.springframework.amqp.rabbit.listener.DirectReplyToMessageListenerContainerTests.java
License:Apache License
@Test public void testReleaseConsumerRace() throws Exception { ConnectionFactory connectionFactory = new CachingConnectionFactory("localhost"); DirectReplyToMessageListenerContainer container = new DirectReplyToMessageListenerContainer( connectionFactory);//from w w w. j av a 2 s. c o m final CountDownLatch latch = new CountDownLatch(1); container.setMessageListener(m -> latch.countDown()); container.start(); ChannelHolder channel1 = container.getChannelHolder(); BasicProperties props = new BasicProperties().builder().replyTo(Address.AMQ_RABBITMQ_REPLY_TO).build(); channel1.getChannel().basicPublish("", TEST_RELEASE_CONSUMER_Q, props, "foo".getBytes()); Channel replyChannel = connectionFactory.createConnection().createChannel(false); GetResponse request = replyChannel.basicGet(TEST_RELEASE_CONSUMER_Q, true); int n = 0; while (n++ < 100 && request == null) { Thread.sleep(100); request = replyChannel.basicGet(TEST_RELEASE_CONSUMER_Q, true); } assertNotNull(request); replyChannel.basicPublish("", request.getProps().getReplyTo(), new BasicProperties(), "bar".getBytes()); replyChannel.close(); assertTrue(latch.await(10, TimeUnit.SECONDS)); ChannelHolder channel2 = container.getChannelHolder(); assertSame(channel1.getChannel(), channel2.getChannel()); container.releaseConsumerFor(channel1, false, null); // simulate race for future timeout/cancel and onMessage() Map<?, ?> inUse = TestUtils.getPropertyValue(container, "inUseConsumerChannels", Map.class); assertThat(inUse.size(), equalTo(1)); container.releaseConsumerFor(channel2, false, null); assertThat(inUse.size(), equalTo(0)); }
From source file:org.springframework.amqp.rabbit.support.RabbitUtils.java
License:Apache License
/** * Close the given RabbitMQ Channel and ignore any thrown exception. This is useful for typical <code>finally</code> * blocks in manual RabbitMQ code.//from ww w. j ava 2 s . c om * @param channel the RabbitMQ Channel to close (may be <code>null</code>) */ public static void closeChannel(Channel channel) { if (channel != null) { try { channel.close(); } catch (IOException ex) { logger.debug("Could not close RabbitMQ Channel", ex); } catch (Throwable ex) { logger.debug("Unexpected exception on closing RabbitMQ Channel", ex); } } }
From source file:org.springframework.cloud.vault.config.rabbitmq.VaultConfigRabbitMqTests.java
License:Apache License
@Test public void shouldConnectUsingRabbitMQClient() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(RABBITMQ_HOST);//from w w w . java 2 s. com factory.setPort(RABBITMQ_PORT); factory.setUsername(username); factory.setPassword(password); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.close(); connection.close(); }
From source file:org.springframework.integration.amqp.inbound.AmqpMessageSourceTests.java
License:Apache License
@Test public void testAck() throws Exception { Channel channel = mock(Channel.class); willReturn(true).given(channel).isOpen(); Envelope envelope = new Envelope(123L, false, "ex", "rk"); BasicProperties props = new BasicProperties.Builder().build(); GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0); willReturn(getResponse).given(channel).basicGet("foo", false); Connection connection = mock(Connection.class); willReturn(true).given(connection).isOpen(); willReturn(channel).given(connection).createChannel(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString()); CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory); AmqpMessageSource source = new AmqpMessageSource(ccf, "foo"); source.setRawMessageHeader(true);//from w w w . j av a2 s. co m Message<?> received = source.receive(); assertThat(received.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE)) .isInstanceOf(org.springframework.amqp.core.Message.class); assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SOURCE_DATA)) .isSameAs(received.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE)); assertThat(received.getHeaders().get(AmqpHeaders.CONSUMER_QUEUE)).isEqualTo("foo"); // make sure channel is not cached org.springframework.amqp.rabbit.connection.Connection conn = ccf.createConnection(); Channel notCached = conn.createChannel(false); // should not have been "closed" verify(connection, times(2)).createChannel(); StaticMessageHeaderAccessor.getAcknowledgmentCallback(received).acknowledge(Status.ACCEPT); verify(channel).basicAck(123L, false); Channel cached = conn.createChannel(false); // should have been "closed" verify(connection, times(2)).createChannel(); notCached.close(); cached.close(); ccf.destroy(); verify(channel, times(2)).close(); verify(connection).close(30000); }
From source file:org.teksme.server.queue.sender.impl.AMQPQueueSenderService.java
License:Apache License
public void publishMessage(InboundMessage inboundMsg) { try {/* w ww .ja v a 2 s .c om*/ Connection lConnection = getAMQPConnServiceReference(); Channel lChannel = lConnection.createChannel(); byte[] data = convertToSend(inboundMsg); // Parameters to constructor for new AMQP.BasicProperties are: // (contentType, contentEncoding, headers, deliveryMode, priority, // correlationId, replyTo, // expiration, messageId, timestamp, type, userId, appId, clusterId) // Here we're just specifying that the message is persistant AMQP.BasicProperties messageProperties = new AMQP.BasicProperties(null, null, null, new Integer(2), null, null, null, null, null, null, null, null, null, null); final String queueName = "teksme.inboundPrimary"; final String routingKey = "sms.inbound"; final String exchange = "teksme.inbound"; logger.info( "Publishing message to queue [" + queueName + "] with routing key [" + routingKey + "] ..."); lChannel.basicPublish(exchange, routingKey, messageProperties, data); lChannel.close(); // lConnection.close(); } catch (Exception lIoException) { throw new RuntimeException(lIoException); } }
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);/*from w w w.j a va 2 s . com*/ 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(); } }