1.下载rabbitmq的javaClient库
文件名:rabbitmq-client.jar
下载地址:http://download.youkuaiyun.com/detail/monkey131499/9440572
下载后将文件导入到项目中。
2.消息发送类
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* send message
* @author monkey
*
*/
public class Send {//发送端
private final static String QUEUE_NAME = "queue_test_1";
static Logger logger = Logger.getLogger(Send.class);
public static void start() throws IOException, TimeoutException
{
//connection制造工厂
ConnectionFactory factory = new ConnectionFactory();
//由于rabbitmq-server安装在本机,故用localhost或127.0.0.1
factory.setHost("localhost");
//创建连接
Connection connection = factory.newConnection();
//创建渠道
Channel channel = connection.createChannel();
//定义queue属性
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "This is the test message~";
//发送消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
logger.info(" [*] Send '" + message + "' to "+QUEUE_NAME+" success!" );
channel.close();
connection.close();
}
}
3.消息接收类
import org.apache.log4j.Logger;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
/**
* receive message
* @author monkey
*
*/
public class Receive {//接收端
//定义queue名称
private final static String QUEUE_NAME = "queue_test_1";
//设置日志
static Logger logger = Logger.getLogger(Receive.class);
public static void start() throws Exception
{
//connection制造工厂
ConnectionFactory factory = new ConnectionFactory();
//由于rabbitmq-server安装在本机,故用localhost或127.0.0.1
factory.setHost("localhost");
//创建连接
Connection connection = factory.newConnection();
//创建渠道
Channel channel = connection.createChannel();
//定义queue属性
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// logger.info("[*] Waiting for messages. To exit press CTRL+C");
boolean noAck = false;
GetResponse response = channel.basicGet(QUEUE_NAME, noAck);
if (response == null) {
logger.info("[*] Waiting for messages. To exit press CTRL+C");
} else {
byte[] body = response.getBody();
long deliveryTag = response.getEnvelope().getDeliveryTag();
String message = new String(body);
logger.info("[**] Received '" + message + "' from "+QUEUE_NAME);
channel.basicAck(deliveryTag, false); // acknowledge receipt of the message
}
channel.close();
connection.close();
}
}
4.主类(运行10000次发送接收消息)
/**
* main
* @author monkey
*
*/
public class Main {
public static void main(String[] args) throws Exception {
int num=10000;
int i=0;
while(i<num){
Send.start();
Receive.start();
i++;
}
}
}
5.测试结果
本文详细介绍了如何使用RabbitMQ的Java客户端库实现消息发送与接收的功能,包括创建连接、建立通道、定义队列、发送与接收消息等关键步骤。通过示例代码展示了从发送端到接收端的完整流程,并提供了运行10000次发送接收消息的主类。
678

被折叠的 条评论
为什么被折叠?



