为了测试RabbitMQ是否好用,编写了一个由Java语言编写的RabbitMQ基本功能测试用例,仅供参考。
代码说明:
由于实现语言是Java,因此有Java虚拟机(安装了JDK或JRE)即可测试,不需要像Python一样需要安装第三方模块,便于Docker环境下做简单测试。在此测试用例用用到了amqp-client-3.x.x.jar库,可以自行下载。
为实现一个java源文件中实现收与发(编译后还是3个Class文件),在main函数中起了两个线程,一个负责发,一个负责收,用来测试RabbitMQ消息的收与发。发送消息是每2s发一次(实现:Java Thread Sleep),为了每次发送消息内容的不同消息内容中加入了Java随机数(实现:Java Random)。
代码如下:
package com.devops.broker.rabbitmq.client; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; import java.io.IOException; import java.util.Random; class send extends Thread { private final static String QUEUE_NAME = "hello"; public void run() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("10.6.28.46"); factory.setPort(5672); factory.setUsername("guest"); factory.setPassword("guest"); Random randomIntNumber = new Random(); try { while (true) { Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello World!"; Long ThreadID = send.currentThread().getId(); message = message + " Thread ID: " + ThreadID.toString() + " Random Num: " + randomIntNumber.nextInt(); channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("Sent ‘" + message + "‘"); System.out.println(""); channel.close(); connection.close(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Exception e) { System.out.println(e.getMessage()); } } } class receiver extends Thread { private final static String QUEUE_NAME = "hello"; public void run() { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("10.6.28.46"); factory.setPort(5672); factory.setUsername("guest"); factory.setPassword("guest"); try { Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); QueueingConsumer consumer = new QueueingConsumer(channel); channel.basicConsume(QUEUE_NAME, true, consumer); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String message = new String(delivery.getBody()); System.out.println("Received ‘" + message + "‘"); } } catch (Exception e) { System.out.println(e.getMessage()); } } } public class Main { public static void main(String[] args) throws IOException { send send = new send(); send.start(); receiver receiver = new receiver(); receiver.start(); } }
tag:RabbitMQ Java demo,测试用例,功能测试
--end--
时间: 2024-10-28 16:17:37