以下代码演示了如何使用RabbitMQ的客户端开发包,进行消息生产和消费。RabbitMQ的客户端开发包可以在RabbitMQ官网进行下载(http://www.rabbitmq.com/java-client.html),也可以使用Mavean官方库进行导入:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.5.4</version>
</dependency>
一、演示前的准备工作
进行具体编码前需要做一些准备工作:
- 创建Exchanges;
- 创建Queues;
- 绑定Exchanges和Queues。
1.1、创建Exchanges
1.2、创建Queues
1.3、绑定Exchanges和Queues
二、具体示例
2.1、RabbitMQ消息生产者
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* 这个测试类,用于模拟消息生成者,每100毫秒,向rabbit集群写入不同的消息
*/
public class RabbitProducerThread implements Runnable {
/**
* 日志
*/
private static final Log LOGGER = LogFactory.getLog(RabbitProducerThread.class);
public static void main(String[] args) throws Exception {
new Thread(new RabbitProducerThread()).start();
}
public void run() {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.1.168");
connectionFactory.setPort(5672);
connectionFactory.setUsername("root");
connectionFactory.setPassword("root");
Connection conn = null;
Channel producerChannel = null;
try {
conn = connectionFactory.newConnection();
producerChannel = conn.createChannel();
} catch (Exception e) {
RabbitProducerThread.LOGGER.error(e.getMessage(), e);
System.exit(-1);
}
// 然后每隔100毫秒,发送一条数据
while (true) {
// 消息的唯一编号
String uuid = UUID.randomUUID().toString();
String message = uuid + ";time=" + new Date().getTime();
// 设置一些参数
BasicProperties properties = new BasicProperties().builder().type("String").contentType("text")
.contentEncoding("UTF-8").messageId(uuid).build();
try {
// 第一个参数是exchange交换器的名字
// 第二个参数是进行消息路由的关键key
producerChannel.basicPublish("test_exchange", "test_routingKey", properties, message.getBytes());
RabbitProducerThread.LOGGER.info("消息发送:" + message);
} catch (IOException e) {
RabbitProducerThread.LOGGER.error(e.getMessage(), e);
}
synchronized (this) {
try {
this.wait(3000);
} catch (InterruptedException e) {
RabbitProducerThread.LOGGER.error(e.getMessage(), e);
}
}
}
}
}
启动后的样子
2.2、RabbitMQ消息消费者
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
/**
* 这个测试类,用于模拟消息消费者
*/
public class RabbitConsumerThread implements Runnable {
/**
* 日志
*/
private static final Log LOGGER = LogFactory.getLog(RabbitConsumerThread.class);
public static void main(String[] args) throws Exception {
new Thread(new RabbitConsumerThread()).start();
}
public void run() {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.1.168");
connectionFactory.setPort(5672);
connectionFactory.setUsername("root");
connectionFactory.setPassword("root");
Connection conn = null;
Channel consumerChannel = null;
try {
conn = connectionFactory.newConnection();
consumerChannel = conn.createChannel();
} catch (Exception e) {
RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
System.exit(-1);
}
// 开始监控消息,(ack是手动的)
QueueingConsumer queueingConsumer = null;
try {
queueingConsumer = new QueueingConsumer(consumerChannel);
// 设置消费者订阅的消息队列名:test_queues
consumerChannel.basicConsume("test_queues", false, queueingConsumer);
} catch (IOException e) {
RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
System.exit(-1);
}
// 停顿200毫秒,才处理下一条,以便模拟事件处理对应的消耗事件
while (true) {
QueueingConsumer.Delivery delivery = null;
try {
delivery = queueingConsumer.nextDelivery();// 如果队列里没有消息,程序会阻塞在这里
} catch (Exception e) {
RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
}
long deliverytag = delivery.getEnvelope().getDeliveryTag();
byte[] messageBytes = delivery.getBody();
BasicProperties properties = delivery.getProperties();
String message = new String(messageBytes);
RabbitConsumerThread.LOGGER.info("收到事件======message = " + message + " | properties =" + properties);
// 这里停顿200毫秒,模拟业务时间
synchronized (this) {
try {
this.wait(200);
} catch (InterruptedException e) {
RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
}
}
RabbitConsumerThread.LOGGER.info("事件message = " + message + "处理完成,发送ack。等待下一条消息");
try {
// 发送ack:消息处理成功的确认信号
consumerChannel.basicAck(deliverytag, false);
} catch (IOException e) {
RabbitConsumerThread.LOGGER.error(e.getMessage(), e);
}
}
}
}
启动后的样子