import com.rabbitmq.client.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeoutException;
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException, NoSuchAlgorithmException, KeyManagementException {
final String host = "rbtmq-xxxxx.rabbitmq.volces.com";
final String username = "demo-user";
final String password = "demo-user-password";
ConnectionFactory factory = new ConnectionFactory();
factory.setUsername(username);
factory.setPassword(password);
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(5000);
factory.setConnectionTimeout(30 * 1000);
factory.setHandshakeTimeout(30 * 1000);
factory.setShutdownTimeout(0);
final String vhost = "/";
final String exchange = "demo-exchange";
final String exchangeType = "direct";
final String queue = "demo-queue";
final String bindingKey = "foo";
factory.setVirtualHost(vhost);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchange, exchangeType, true, false, false, null);
HashMap<String, Object> arg = new HashMap<>();
channel.queueDeclare(queue, true, false, false, arg);
channel.queueBind(queue, exchange, bindingKey);
channel.basicConsume(queue, false, "consumertag", new DefaultConsumer(channel) {
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
System.out.printf("receive message: " + new String(body, StandardCharsets.UTF_8) + ", deliveryTag: " + envelope.getDeliveryTag() + ", messageId: " + properties.getMessageId());
channel.basicAck(envelope.getDeliveryTag(), false);
CountDownLatch latch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
channel.getConnection().close();
} catch (IOException e) {
System.out.println("close connection error." + e);