RabbitMQ异步发送一个map,并且在另一端接收
时间: 2024-02-28 19:20:26 浏览: 82
c# RabbitMQ封装类,连接发送接收解析都支持
5星 · 资源好评率100%
你可以使用RabbitMQ的发布-订阅模式来实现异步发送一个map,并在另一端接收。下面是一个示例代码,演示了如何使用RabbitMQ的Java客户端库来实现这个功能:
发送端代码:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
public class Sender {
private final static String QUEUE_NAME = "my_queue";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Map<String, Object> message = new HashMap<>();
message.put("key1", "value1");
message.put("key2", "value2");
channel.basicPublish("", QUEUE_NAME, null, SerializationUtils.serialize(message));
System.out.println("Message sent");
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
```
接收端代码:
```java
import com.rabbitmq.client.*;
import org.apache.commons.lang3.SerializationUtils;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeoutException;
public class Receiver {
private final static String QUEUE_NAME = "my_queue";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
Map<String, Object> message = SerializationUtils.deserialize(body);
System.out.println("Received message: " + message);
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
}
```
这段代码中,发送端创建了一个名为"my_queue"的队列,并将一个包含键值对的map序列化后发送到该队列。接收端监听该队列,一旦有消息到达,就会将接收到的字节数组反序列化为map,并进行处理。
确保在运行代码之前,你已经安装并启动了RabbitMQ服务器。这个示例使用的是本地主机(localhost)作为RabbitMQ服务器的地址,你可以根据实际情况进行修改。
阅读全文