分布式消息服务RabbitMQ版-不使用SSL证书连接:示例代码(Java)

时间:2023-11-01 16:15:34

示例代码(Java)

连接实例并生产消息

ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); 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();

连接实例并消费消息

ConnectionFactory factory = new ConnectionFactory(); factory.setHost(host); factory.setPort(port); 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/qs-rabbitmq/rabbitmq-qs-005.html