创建一个项目,添加rabbitmq 的依赖jar包
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.5.3</version>
</dependency>
之后创建一个生产者,一个消费者, 注意,端口号不要写错,否则链接异常
消费者
package quickstart;
import com.rabbitmq.client.*;
public class Consumer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
// 2通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();
// 3通过connection 创建一个Channel
Channel channel = connection.createChannel();
// 4 声明一个队列
String queueName = "test001";
channel.queueDeclare(queueName, true, false, false, null);
// 5.创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
// 6 设置channel
channel.basicConsume(queueName, true, queueingConsumer);
while (true) {
//nextDelivery() 一个有参数,一个无参数 , 无参数会一直阻塞
// 7 获取消息
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("消费端: " + msg);
Envelope envelope = delivery.getEnvelope();
}
}
}
生产者
package quickstart;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Procuder {
public static void main(String[] args) throws IOException, TimeoutException {
// 创建一个ConnectionFactory 工厂, 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
connectionFactory.setPort(5672);
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
connectionFactory.setVirtualHost("/");
Connection connection = null;
Channel channel = null;
try {
// 2通过连接工厂创建连接
connection = connectionFactory.newConnection();
// 3通过connection 创建一个Channel
channel = connection.createChannel();
// 4通过Channel发送数据
for (int i = 0 ; i < 5 ; i++){
String msg = "Hello RabbitMQ";
channel.basicPublish("", "test001", null, msg.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
// 记得关闭相关连接
if (channel != null) {
channel.close();
}
if (connection != null) {
connection.close();
}
}
}
}
运行消费者,和生产者,输出
Hello RabbitMQ, 这里循环了5次,相当于发了五次,好了,简单的入门案例