微服务基础篇:MQ(MessageQueue)消息队列(同步异步通讯,RabbitMQ快速入门,SpringAMQP,简单队列模型,工作队列模型,发布订阅模型,消息转换器)
消息队列(MQ)是一种软件应用,它可以实现进程或服务之间的通信。这种通信可以基于同步或异步的方式,可以是点对点或发布/订阅模式。
RabbitMQ是一种流行的开源消息队列系统,它遵循AMQP(高级消息队列协议)标准。
以下是RabbitMQ快速入门的代码示例:
- 引入依赖(Maven):
<dependencies>
<!-- RabbitMQ Java client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.9.0</version>
</dependency>
</dependencies>
- 生产者(发送消息):
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
// 创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
// 创建连接和通道
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
// 声明一个队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
// 发布消息到队列中
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
}
}
}
- 消费者(接收消息):
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
// 创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
// 创建连接和通道
try (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");
// 创建队列消费者
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
}
以上代码演示了如何使用RabbitMQ和Java客户端库创建一个简单的消息队列,生产者发送消息到队列,消费者从队列中接收消息。
评论已关闭