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

The following examples show how to use com.rabbitmq.client.Connection#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 code with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException {
    //1、创建一个ConnectionFactory, 并进行配置
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost(Constant.ip);
    connectionFactory.setPort(Constant.port);
    connectionFactory.setVirtualHost("/");

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

    //3、通过connection创建一个Channel
    Channel channel = connection.createChannel();

    //4、通过Channel发送数据
    for (int i = 0; i < 5; i++) {
        String msg = "Hello RabbitMQ!";
        //1 exchange   2 routingKey
        channel.basicPublish("", "test001", null, msg.getBytes());
    }

    //5、记得要关闭相关的连接
    channel.close();
    connection.close();
}
 
Example 2
Source File: Producer.java    From SpringBoot-Course with MIT License 6 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 fanoutExchangeName = "fanout_exchange_name";
    String fanoutRoutingKey = "";
    String fanoutMsg = "fanout hello world";

    channel.basicPublish(fanoutExchangeName, fanoutRoutingKey, null, fanoutMsg.getBytes());

    // 关闭链接
    channel.close();
    connection.close();
}
 
Example 3
Source File: NewTask.java    From rabbitmq with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] argv) throws java.io.IOException, Exception {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("localhost");
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
//		�ַ���Ϣ
		for(int i = 0 ; i < 5; i++){
			String message = "Hello World! " + i;
			channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");
		}
		channel.close();
		connection.close();
	}
 
Example 4
Source File: SimpleConnectionPool.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mono<Connection> getOpenConnection() {
    Connection previous = connectionReference.get();
    Connection current = Optional.ofNullable(previous)
        .filter(Connection::isOpen)
        .orElseGet(connectionFactory::create);
    boolean updated = connectionReference.compareAndSet(previous, current);
    if (updated) {
        return Mono.just(current);
    } else {
        try {
            current.close();
        } catch (IOException e) {
            //error below
        }
        return Mono.error(new RuntimeException("unable to create and register a new Connection"));
    }
}
 
Example 5
Source File: ConsumeAMQP.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected synchronized AMQPConsumer createAMQPWorker(final ProcessContext context, final Connection connection) {
    try {
        final String queueName = context.getProperty(QUEUE).getValue();
        final boolean autoAcknowledge = context.getProperty(AUTO_ACKNOWLEDGE).asBoolean();
        final AMQPConsumer amqpConsumer = new AMQPConsumer(connection, queueName, autoAcknowledge);

        return amqpConsumer;
    } catch (final IOException ioe) {
        try {
            connection.close();
            getLogger().warn("Closed connection at port " + connection.getPort());
        } catch (final IOException ioeClose) {
            throw new ProcessException("Failed to close connection at port " + connection.getPort());
        }

        throw new ProcessException("Failed to connect to AMQP Broker", ioe);
    }
}
 
Example 6
Source File: Producer.java    From SpringBoot-Course with MIT License 6 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.close();
    connection.close();
}
 
Example 7
Source File: AMQPPublisherTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void validateSuccessfullPublishingAndUndeliverableRoutingKey() throws Exception {
    Map<String, List<String>> routingMap = new HashMap<>();
    routingMap.put("key1", Arrays.asList("queue1", "queue2"));
    Map<String, String> exchangeToRoutingKeymap = new HashMap<>();
    exchangeToRoutingKeymap.put("myExchange", "key1");

    Connection connection = new TestConnection(exchangeToRoutingKeymap, routingMap);

    ReturnListener retListener = mock(ReturnListener.class);
    connection.createChannel().addReturnListener(retListener);

    try (AMQPPublisher sender = new AMQPPublisher(connection, new MockComponentLog("foo", ""))) {
        sender.publish("hello".getBytes(), null, "key1", "myExchange");
        Thread.sleep(1000);
    }
    Thread.sleep(200);
    verify(retListener, atMost(1)).handleReturn(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyString(), Mockito.any(BasicProperties.class), (byte[]) Mockito.any());
    connection.close();
}
 
Example 8
Source File: ProducerExchangeConsumer_Fanout.java    From util4j with Apache License 2.0 6 votes vote down vote up
public void producer() throws Exception{
    	 //1、获取连接
        Connection connection = RabbitMqConnectionFactoy.getConnection();
        //2、声明信道
        Channel channel = connection.createChannel();
        //3、声明(创建)交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        Thread.sleep(3000);
        //4、定义消息内容(发布多条消息)
        for(int i = 0 ; i < 10 ; i++){
            String message = "hello rabbitmq "+i;
            //定义消息头
            Map<String,Object> header=new HashMap<>();
            header.put("i",i);
            BasicProperties bp=new BasicProperties.Builder().headers(header).build();
            //5、发布消息
            channel.basicPublish(EXCHANGE_NAME,"",bp,message.getBytes());
            System.out.println("[x] Sent'"+message+"'");
            //模拟发送消息延时,便于演示多个消费者竞争接受消息
//            Thread.sleep(i*10);
        }
        //6、关闭通道
        channel.close();
        //7、关闭连接
        connection.close();
    }
 
Example 9
Source File: RoutingSendDirect.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, "direct");
//		������Ϣ
        for(String severity :routingKeys){
        	String message = "Send the message level:" + severity;
        	channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes());
        	System.out.println(" [x] Sent '" + severity + "':'" + message + "'");
        }
        channel.close();
        connection.close();
    }
 
Example 10
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 11
Source File: ProducerExchangeConsumer_Topic.java    From util4j with Apache License 2.0 5 votes vote down vote up
public void producer() throws Exception{
	 //1、获取连接
    Connection connection = RabbitMqConnectionFactoy.getConnection();
    //2、声明信道
    Channel channel = connection.createChannel();
    //3、声明(创建)交换机
    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
    Thread.sleep(3000);
    //4、定义消息内容(发布多条消息)
    for(int i = 0 ; i < 10 ; i++){
        String message = "hello rabbitmq "+i;
        //定义消息头
        Map<String,Object> header=new HashMap<>();
        header.put("i",i);
        BasicProperties bp=new BasicProperties.Builder().headers(header).build();
        //5、发布消息
        if(i%2!=0)
        {//单数进key1的队列
        	 channel.basicPublish(EXCHANGE_NAME,"test.a",bp,message.getBytes());
        }else
        {//偶数进key2的队列
        	 channel.basicPublish(EXCHANGE_NAME,"test.b",bp,message.getBytes());
        }
        System.out.println("[x] Sent'"+message+"'");
        //模拟发送消息延时,便于演示多个消费者竞争接受消息
        Thread.sleep(i*10);
    }
    //6、关闭通道
    channel.close();
    //7、关闭连接
    connection.close();
}
 
Example 12
Source File: Send.java    From java-study with Apache License 2.0 5 votes vote down vote up
public static void main(String[] argv) throws Exception {
         Map map=new HashMap();  
         map.put("aa", 11);
         map.put("bb", 22);
         map.put("cc", 33);
         map.put("dd", 44);
         map.put("ff", 1);
System.out.println("你好啊!");
    //创建连接连接到MabbitMQ 
  ConnectionFactory factory = new ConnectionFactory();
  // 设置MabbitMQ所在主机ip或者主机名  
  // factory.setHost("localhost");
  //factory.setHost("127.0.0.1");
  
factory.setUri("amqp://guest:[email protected]:5672");//获取url
  // 创建一个连接  
  Connection connection = factory.newConnection();
  // 创建一个频道 
  Channel channel = connection.createChannel();
  // 指定一个队列  
  channel.queueDeclare(QUEUE_NAME, false, false, false, null);
  //发送的消息
  String message = JSON.toJSONString(map); 
  // 往队列中发出一条消息 
  channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); //发送
  System.out.println(" [x] Sent '" + message + "'");
  // 关闭频道和连接  
  channel.close();
  connection.close();
  
  
  
}
 
Example 13
Source File: RabbitMqTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    EmbeddedRabbitMqConfig configuration = new EmbeddedRabbitMqConfig.Builder()
            // 时间过短会启动失败
            .rabbitMqServerInitializationTimeoutInMillis(60000)
            // 时间过短会停止失败
            .defaultRabbitMqCtlTimeoutInMillis(60000)

            .build();
    EmbeddedRabbitMq rabbitMq = new EmbeddedRabbitMq(configuration);
    try {
        rabbitMq.start();

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

        Connection connection = connectionFactory.newConnection();
        Assert.assertTrue(connection.isOpen());
        Channel channel = connection.createChannel();
        Assert.assertTrue(channel.isOpen());
        channel.close();
        Assert.assertFalse(channel.isOpen());
        connection.close();
        Assert.assertFalse(connection.isOpen());
    } finally {
        rabbitMq.stop();
    }
}
 
Example 14
Source File: NegativeQueueDeleteTest.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
@Parameters({"broker-hostname", "broker-port", "admin-username", "admin-password"})
@AfterMethod
public void tearDown(String hostname, String port, String username, String password) throws Exception {
    Connection connection = ClientHelper.getAmqpConnection(username, password, hostname, port);
    Channel channel = connection.createChannel();
    channel.queueDelete(queueWithConsumers);
    channel.queueDelete(queueWithMessages);
    connection.close();
    this.amqpConnection.close();
}
 
Example 15
Source File: RabbitMqClientDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setUsername(XianConfig.get("rabbitmqUserName"));
    factory.setPassword(XianConfig.get("rabbitmqPwd"));
    factory.setVirtualHost("/");
    factory.setHost("production-internet-mq.apaycloud.com");
    factory.setPort(5672);
    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();


    String exchangeName = "yy-exchange";
    String routingKey = "yy-routingKey";
    String queueName = "yy-queueName";

    channel.exchangeDeclare(exchangeName, "direct", true);
    channel.queueDeclare(queueName, true, false, false, null);
    channel.queueBind(queueName, exchangeName, routingKey);

    byte[] messageBodyBytes = "Hello, world2!".getBytes();
    channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);


    Thread.sleep(1000 * 60);

    channel.close();
    conn.close();
}
 
Example 16
Source File: NewTask.java    From demo_springboot_rabbitmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, TimeoutException {

        //建立连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置连接地址
        factory.setHost("seaof-153-125-234-173.jp-tokyo-10.arukascloud.io");
        factory.setPort(31084);
        //获取连接
        Connection connection = factory.newConnection();
        //获取渠道
        Channel channel = connection.createChannel();
        //声明队列,如果不存在就新建
        //参数1队列名称;参数2是否持久化;参数3排他性队列,连接断开自动删除;参数4是否自动删除;参数5.参数
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //发送的消息
        for (int i = 0; i < 10; i++) {

            String message = "Hello";
            int num = ThreadLocalRandom.current().nextInt(10);
            String append = "";
            for (int j = 0; j < num; j++) {
                append = append + ".";
            }
            message = message + (append);

            //参数1 交换机;参数2 路由键;参数3 基础属性,(持久化方式);参数4 消息体
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
            System.out.println(Thread.currentThread().getName() + "[send]" + message);
        }
        channel.close();
        connection.close();


    }
 
Example 17
Source File: Producer.java    From code with Apache License 2.0 5 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 = connectionFactory.newConnection();
	
	//3 通过connection创建一个Channel
	Channel channel = connection.createChannel();

	// 自定义属性
	Map<String, Object> headers = new HashMap<>();
	headers.put("my1", "111");
	headers.put("my2", "222");

	AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
			.deliveryMode(2)
			.contentEncoding("UTF-8")
			.expiration("10000")
			.headers(headers)
			.build();
	
	//4 通过Channel发送数据
	for(int i=0; i < 5; i++){
		String msg = "Hello RabbitMQ!";
		//1 exchange   2 routingKey
		channel.basicPublish("", "test001", properties, msg.getBytes());
	}

	//5 记得要关闭相关的连接
	channel.close();
	connection.close();
}
 
Example 18
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 19
Source File: RabbitMQSender.java    From zipkin-reporter-java with Apache License 2.0 4 votes vote down vote up
@Override public synchronized void close() throws IOException {
  if (closeCalled) return;
  Connection connection = this.connection;
  if (connection != null) connection.close();
  closeCalled = true;
}
 
Example 20
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;
}