Maven依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.14.0</version>
</dependency>
生产端代码
package org.ysy.study.rabbitmq;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Desc: HelloWorldSender
* Created ysy on 2021/12/29 15:30.
*/
public class HelloWorldSender {
private static Logger logger = LoggerFactory.getLogger(HelloWorldSender.class);
public static void main(String args[]) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
String queue = "HelloWorld";
boolean durable = false;
boolean exclusive = false;
boolean autoDelete = false;
Map<String, Object> arguments = null;
channel.queueDeclare(queue, durable, exclusive, autoDelete, arguments);
String message = "hello world " + System.currentTimeMillis();
String exchange = "";
String routingKey = queue;
AMQP.BasicProperties props = null;
byte[] body = message.getBytes();
channel.basicPublish(exchange, routingKey, props, body);
logger.info("发送消息 : {}", message);
}
}
}
运行输出日志:
16:16:09.835 [main] INFO org.ysy.study.rabbitmq.HelloWorldSender - 发送消息 : hello world 1640765769832
消费端代码
package org.ysy.study.rabbitmq;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* Desc: HelloWorldReceiver
* Created ysy on 2021/12/29 15:49.
*/
public class HelloWorldReceiver {
private static Logger logger = LoggerFactory.getLogger(HelloWorldReceiver.class);
public static void main(String args[]) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
String queue = "HelloWorld";
boolean durable = false;
boolean exclusive = false;
boolean autoDelete = false;
Map<String, Object> arguments = null;
channel.queueDeclare(queue, durable, exclusive, autoDelete, arguments);
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
logger.info("收到消息 {}", message);
};
channel.basicConsume(queue, true, deliverCallback, consumerTag -> {
});
logger.info("开始监听消息。。。");
}
}
输出日志
16:17:16.787 [main] INFO org.ysy.study.rabbitmq.HelloWorldReceiver - 开始监听消息。。。
16:17:16.796 [pool-1-thread-4] INFO org.ysy.study.rabbitmq.HelloWorldReceiver - 收到消息 hello world 1640765769832