1. pom.xml
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.1.0</version>
</dependency>
2 . 接收端
package com.niewj.service;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.util.concurrent.TimeoutException;
public class Recv {
//队列名称
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws java.io.IOException, java.lang.InterruptedException, TimeoutException {
//打开连接和创建频道,与发送端一样
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("123456");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//声明队列,主要为了防止消息接收者先运行此程序,队列还不存在时创建队列。
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
// //创建队列消费者
// DefaultConsumer consumer = new DefaultConsumer(channel);
// //指定消费队列
// channel.basicConsume(QUEUE_NAME, true, consumer);
// while (true) {
// //nextDelivery是一个阻塞方法(内部实现其实是阻塞队列的take方法)
// DefaultConsumer.Delivery delivery = consumer.nextDelivery();
// String message = new String(delivery.getBody());
// System.out.println(" [x] Received '" + message + "'");
// }
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] 接收消息 '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
3. 发送端
package com.niewj.service;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.concurrent.TimeoutException;
public class Send {
//队列名称
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws java.io.IOException, TimeoutException {
//创建连接连接到MabbitMQ
ConnectionFactory factory = new ConnectionFactory();
//设置MabbitMQ所在主机ip或者主机名
factory.setHost("localhost");
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("123456");
//创建一个连接
Connection connection = factory.newConnection();
//创建一个频道
Channel channel = connection.createChannel();
//指定一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//发送的消息
String message = "{\"name\": \"nie\" }, \"online\": false}";
//往队列中发出一条消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] 发送 '" + message + "'");
//关闭频道和连接
channel.close();
connection.close();
}
}
启动接受端, 然后使用发送端发消息,便可以接收到。