导入依赖
com.rabbitmq
amqp-client
5.6.0
编写工具类
public class RabbitMQUtil {
private static Connection connection;
public static synchronized Connection getConnection() throws Exception {
if (connection == null) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/");
factory.setUsername("guest");
factory.setPassword("guest");
connection = factory.newConnection();
}
return connection;
}
}
编写生产者
public class RabbitMQProducer {
public static void main(String[] args) throws Exception {
// 1. 获取连接
Connection connection = RabbitMQUtil.getConnection();
// 2. 获取通道
Channel channel = connection.createChannel();
// 3. 创建交换机
channel.exchangeDeclare("test_exchange", BuiltinExchangeType.TOPIC, true);
// 4. 创建队列
channel.queueDeclare("test_queue_1",true,false,false,null);
channel.queueDeclare("test_queue_2",true,false,false,null);
channel.queueDeclare("test_queue_3",true,false,false,null);
// 5. 绑定队列和交换机
channel.queueBind("test_queue_1","test_exchange", "#.world");
channel.queueBind("test_queue_2","test_exchange", "hello.#");
channel.queueBind("test_queue_3","test_exchange", "hello.world");
// 6. 发送消息
for (int i = 0; i < 5; i++) {
channel.basicPublish("test_exchange", "hello.world",null, "hello, world".getBytes());
}
// 7. 关闭资源
channel.close();
connection.close();
}
}
编写消费者
public class RabbitMQConsumer {
public static void main(String[] args) throws Exception {
Connection connection = RabbitMQUtil.getConnection();
Thread consumer1 = new Thread(new ConsumerThread(connection, "test_queue_1"));
consumer1.start();
Thread consumer2 = new Thread(new ConsumerThread(connection, "test_queue_2"));
consumer2.start();
Thread consumer3 = new Thread(new ConsumerThread(connection, "test_queue_3"));
consumer3.start();
}
static class ConsumerThread implements Runnable {
private Connection connection;
private String queue;
public ConsumerThread(Connection connection, String queue) {
this.connection = connection;
this.queue = queue;
}
public void run() {
try {
Channel channel = connection.createChannel();
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(queue + ": " + new String(body));
}
};
channel.basicConsume(queue, true, consumer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}