以下是一个示例代码,演示如何在RabbitMQ监听器中为每个消费者启动一个线程:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;
import java.io.IOException;
public class RabbitMQListenerExample {
private static final String QUEUE_NAME = "my_queue";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try {
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
// 设置每个消费者最大预取数量为1
channel.basicQos(1);
// 创建消费者
for (int i = 1; i <= 3; i++) {
String consumerName = "Consumer" + i;
channel.basicConsume(QUEUE_NAME, false, consumerName, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
// 模拟处理消息的耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(consumerName + " Received: " + message);
// 手动确认消息
channel.basicAck(envelope.getDeliveryTag(), false);
}
});
}
// 等待用户输入来退出程序
System.out.println("按任意键退出程序...");
System.in.read();
// 关闭连接
channel.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码中,我们创建了一个名为"my_queue"的队列,并为每个消费者启动了一个线程进行消息处理。我们使用basicQos
方法设置每个消费者的最大预取数量为1,以确保每个消费者一次只处理一个消息。在消费者的handleDelivery
方法中,我们模拟了一个耗时操作(1秒钟的休眠),然后打印出收到的消息。最后,我们使用basicAck
方法手动确认消息的处理完成。
请注意,上述示例中的代码只是一个简单的示例,实际使用时可能需要进行一些修改来满足具体需求。