Java Code Examples for com.rabbitmq.client.Channel#close()

The following examples show how to use com.rabbitmq.client.Channel#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Producer.java    From rabbitmqexample with Apache License 2.0 7 votes vote down vote up
public void SendResponse(String uuidrequest,String jsonResponse,String RoutingKey) {
	try 
	{
		//System.out.println("Sending back the result");
		
		Channel channel = connection.createChannel();
		AMQP.BasicProperties.Builder bob = new AMQP.BasicProperties.Builder();
		Map<String, Object> header = new HashMap<String,Object> ();
		header.put("uuidrequest", uuidrequest);
		bob.headers(header);
	//	System.out.println("Request: " + guidRequest);

		channel.basicPublish(Constants.exchange, RoutingKey, bob.build(), jsonResponse.getBytes()); 		
		channel.close();
		System.out.println(new Date()+ " -Done: messages sent: " + uuidrequest);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: BindingsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "bindingData")
public void testCreateBinding(String queueName, String bindingPattern) throws IOException, TimeoutException {

    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());
    String exchangeName = "amq.direct";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                   .exchangeName(exchangeName);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);

    BindingCreateResponse responseMessage = HttpClientHelper.getResponseMessage(response,
                                                                                BindingCreateResponse.class);
    Assert.assertEquals(responseMessage.getMessage(), "Binding created.");

    channel.queueUnbind(queueName, exchangeName, bindingPattern);
    channel.close();
}
 
Example 3
Source File: Producer4FanoutExchange.java    From code with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	//1 创建ConnectionFactory
	ConnectionFactory connectionFactory = new ConnectionFactory();
	connectionFactory.setHost(Constant.ip);
	connectionFactory.setPort(Constant.port);
	connectionFactory.setVirtualHost("/");
	
	//2 创建Connection
	Connection connection = connectionFactory.newConnection();
	//3 创建Channel
	Channel channel = connection.createChannel();  
	//4 声明
	String exchangeName = "test_fanout_exchange";
	//5 发送
	for(int i = 0; i < 10; i ++) {
		String msg = "Hello World RabbitMQ 4 FANOUT Exchange Message ...";
		// routingKey随便写
		channel.basicPublish(exchangeName, "", null , msg.getBytes()); 			
	}
	channel.close();  
       connection.close();  
}
 
Example 4
Source File: EmitLog.java    From rabbitmq with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

//		�ַ���Ϣ
		for(int i = 0 ; i < 5; i++){
			String message = "Hello World! " + i;
			 channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
		     System.out.println(" [x] Sent '" + message + "'");
		}
        channel.close();
        connection.close();
    }
 
Example 5
Source File: BindingsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "bindingData")
public void testCreateBindingWithInvalidExchange(String queueName, String bindingPattern)
        throws IOException, TimeoutException {
    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());
    channel.close();
    String exchangeName = "InvalidExchange";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                 .exchangeName(exchangeName);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_BAD_REQUEST);

    Error error = HttpClientHelper.getResponseMessage(response, Error.class);

    Assert.assertFalse(error.getMessage().isEmpty());
}
 
Example 6
Source File: RpcTest.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void rpcServer() throws Exception {
 	//1、获取连接
       Connection connection = RabbitMqConnectionFactoy.getConnection();
       //2、声明信道
       Channel channel = connection.createChannel();
       //3、声明队列
       channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
       channel.basicQos(1);
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           public void handleDelivery(String consumerTag, Envelope envelope,BasicProperties properties, byte[] body)
                   throws IOException {
               //获取并转成String
               String message = new String(body, "UTF-8");
               String cid=properties.getCorrelationId();
               System.out.println("server-->收到消息,msg :"+message+",cid:"+cid);
               String rsp=message+" rsp";
               // 返回处理结果队列
                  channel.basicPublish("", properties.getReplyTo(), properties,rsp.getBytes("UTF-8"));
                  //  确认消息,已经收到后面参数 multiple:是否批量.true:将一次性确认所有小于envelope.getDeliveryTag()的消息。
                  channel.basicAck(envelope.getDeliveryTag(), false);
           }
       };
       channel.basicConsume(RPC_QUEUE_NAME, autoAck,consumer);
       Thread.sleep(1000000);
       //6、关闭通道
       channel.close();
       //7、关闭连接
       connection.close();
}
 
Example 7
Source File: Producer.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 创建链接工厂
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    // 通过链接工厂创建链接
    Connection connection = connectionFactory.newConnection();

    // 通过链接创建通道(channel)
    Channel channel = connection.createChannel();

    // 通过 channel 发送数据
    // exchange:交换机,如果不传默认为 AMQP default
    String directExchangeName = "direct_exchange_name";
    String directRoutingKey = "direct_routingKey";
    String directMsg = "direct hello world";

    channel.basicPublish(directExchangeName, directRoutingKey, null, directMsg.getBytes());
    channel.basicPublish(directExchangeName, directRoutingKey, null, directMsg.getBytes());
    channel.basicPublish(directExchangeName, directRoutingKey, null, directMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 8
Source File: Producer.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 创建链接工厂
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    // 通过链接工厂创建链接
    Connection connection = connectionFactory.newConnection();

    // 通过链接创建通道(channel)
    Channel channel = connection.createChannel();

    // 通过 channel 发送数据
    // exchange:交换机,如果不传默认为 AMQP default
    String dlxExchangeName = "dlx_exchange_name";
    String dlxRoutingKey = "dlx_routingKey";
    String dlxMsg = "dlx hello world";

    AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
            .deliveryMode(2)
            .contentEncoding("UTF-8")
            .expiration("5000") // 设置 5 秒中过期
            .build();

    channel.basicPublish(dlxExchangeName, dlxRoutingKey, basicProperties, dlxMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 9
Source File: RabbitProducer.java    From java-study with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
   //创建连接连接到RabbitMQ 
  ConnectionFactory factory = new ConnectionFactory();
  // 设置ip
  factory.setHost("127.0.0.1");
  /*   //设置端口
  factory.setPort(15672);
  //设置用户名
  factory.setUsername("guest");
  //设置密码
  factory.setPassword("guest");
 //设置url(包括ip、端口、用户名、密码)
  factory.setUri("amqp://guest:guest@localhost:15672");
*/	
  // 创建一个连接  
  Connection connection = factory.newConnection();
  // 创建一个频道 
  Channel channel = connection.createChannel();
  // 指定一个队列  
  channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  Map<String,Object> map=new HashMap<String,Object>();  
    map.put("java", "hello");
    map.put("RabbitMQ", "Hello");
  //发送的消息
  String message = JSON.toJSONString(map); 
  // 往队列中发出一条消息 
  channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); 
  System.out.println(" [x] Sent '" + message + "'");
  // 关闭频道和连接  
  channel.close();
  connection.close();   
}
 
Example 10
Source File: ClientMain.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
    LOG.info("Client Service starting ...");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost:15672/virtualHost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare("exchangeName", "direct", true);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, "exchangeName", "publishKey");

    channel.close();
    connection.close();
}
 
Example 11
Source File: RabbitMQProducerUtil.java    From flink-learning with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //设置RabbitMQ相关信息
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);

        //创建一个新的连接
        Connection connection = factory.newConnection();

        //创建一个通道
        Channel channel = connection.createChannel();

        // 声明一个队列
//        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        //发送消息到队列中
        String message = "Hello zhisheng";

        for (int i = 0; i < 1000; i++) {
            channel.basicPublish("", QUEUE_NAME, null, (message + i).getBytes("UTF-8"));
            System.out.println("Producer Send +'" + message + i);
        }

        //关闭通道和连接
        channel.close();
        connection.close();
    }
 
Example 12
Source File: RabbitPipeImpl.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
private void closeChannel()
{
  if (_channel != null) {
    try {
      Channel channel = _channel;
      _channel = null;

      channel.close();
    }
    catch (Exception e) {
    }
  }
}
 
Example 13
Source File: ExchangeSender.java    From eip with MIT License 5 votes vote down vote up
public static void main(String[] argv) throws java.io.IOException, TimeoutException {
    Rabbit rabbit = new Rabbit("localhost");
    Channel channel = rabbit.createChannel();

    channel.exchangeDeclare(EXCHANGE_NAME, "direct");

    sendMessage(channel, EXCHANGE_NAME, "Widget", "Hello EIP Widget!");
    sendMessage(channel, EXCHANGE_NAME, "Gadget", "Hello EIP Gadget!");

    channel.close();
    rabbit.close();
}
 
Example 14
Source File: Producer.java    From SpringBoot-Course with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 创建链接工厂
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    // 通过链接工厂创建链接
    Connection connection = connectionFactory.newConnection();

    // 通过链接创建通道(channel)
    Channel channel = connection.createChannel();

    // 通过 channel 发送数据
    // exchange:交换机,如果不传默认为 AMQP default
    String topicExchangeName = "topic_exchange_name";
    String topicRoutingKey1 = "topic_routingKey.test1";
    String topicRoutingKey2 = "topic_routingKey.test2";
    String topicRoutingKey3 = "topic_routingKey.test3.test03";
    String topicMsg = "topic hello world";

    channel.basicPublish(topicExchangeName, topicRoutingKey1, null, topicMsg.getBytes());
    channel.basicPublish(topicExchangeName, topicRoutingKey2, null, topicMsg.getBytes());
    channel.basicPublish(topicExchangeName, topicRoutingKey3, null, topicMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 15
Source File: RabbitMqUtils.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the connection to a channel.
 * @param channel the channel to close (can be null)
 * @throws IOException if something went wrong
 */
public static void closeConnection( Channel channel ) throws IOException {

	if( channel != null ) {
		if( channel.isOpen())
			channel.close();

		if( channel.getConnection().isOpen())
			channel.getConnection().close();
	}
}
 
Example 16
Source File: RabbitMQClient.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void destroyObject(PooledObject<Channel> p) throws Exception {
    Channel channel = p.getObject();
    channel.close();
}
 
Example 17
Source File: AMQPCommon.java    From reactive with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
public static void close(Channel channel) throws Exception {
	channel.close();
	channel.getConnection().close();
}
 
Example 18
Source File: ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation() + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if(chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}
 
Example 19
Source File: RabbitMqIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteExchange() throws Exception {
  final int maxNumRecords = 1000;
  List<RabbitMqMessage> data =
      RabbitMqTestUtils.generateRecords(maxNumRecords).stream()
          .map(RabbitMqMessage::new)
          .collect(Collectors.toList());
  p.apply(Create.of(data))
      .apply(
          RabbitMqIO.write()
              .withUri("amqp://guest:guest@localhost:" + port)
              .withExchange("WRITE", "fanout"));

  final List<String> received = new ArrayList<>();
  ConnectionFactory connectionFactory = new ConnectionFactory();
  connectionFactory.setUri("amqp://guest:guest@localhost:" + port);
  Connection connection = null;
  Channel channel = null;
  try {
    connection = connectionFactory.newConnection();
    channel = connection.createChannel();
    channel.exchangeDeclare("WRITE", "fanout");
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, "WRITE", "");
    Consumer consumer = new RabbitMqTestUtils.TestConsumer(channel, received);
    channel.basicConsume(queueName, true, consumer);

    p.run();

    while (received.size() < maxNumRecords) {
      Thread.sleep(500);
    }

    assertEquals(maxNumRecords, received.size());
    for (int i = 0; i < maxNumRecords; i++) {
      assertTrue(received.contains("Test " + i));
    }
  } finally {
    if (channel != null) {
      channel.close();
    }
    if (connection != null) {
      connection.close();
    }
  }
}
 
Example 20
Source File: RabbitConnectionFactory.java    From AsuraFramework with Apache License 2.0 3 votes vote down vote up
/**
 * 关闭连接、关闭通道
 *
 * @param channel
 * @throws IOException
 * @throws TimeoutException
 * @author zhangshaobin
 * @created 2016年3月1日 下午4:36:57
 */
public void closeChannel(Channel channel) throws IOException, TimeoutException {
    if (channel != null) {
        channel.close();
    }

}