分布式消息服务RabbitMQ版-使用客户端连接RabbitMQ(关闭SSL):示例代码(Java)

时间:2025-02-12 15:09:34

示例代码(Java)

  • 连接实例并生产消息示例代码:
    • VHOST_NAME:消息要发送的Queue所在的Vhost名称。
    • QUEUE_NAME:消息要发送的Queue名称。
    • Hello World!:要发送的消息,根据实际需要修改。
    ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); factory.setVirtualHost("VHOST_NAME"); factory.setUsername(user); factory.setPassword(password); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent '" + message + "'"); channel.close(); connection.close();
  • 连接实例并消费消息示例代码:
    • VHOST_NAME:要消费消息的Queue所在的Vhost名称。
    • QUEUE_NAME:要消费消息的Queue名称。
    ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); factory.setVirtualHost("VHOST_NAME"); factory.setUsername(user); 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. To exit press CTRL+C"); 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);
support.huaweicloud.com/usermanual-rabbitmq/rabbitmq-ug-180604009.html