java 语言 实现rabbitMQ 发送 对象数据,接收端处理对象数据
时间: 2024-02-11 21:06:24 浏览: 77
在 Java 语言中,您可以使用 RabbitMQ 的 Java 客户端库来发送和接收对象数据。以下是一个示例代码片段,演示如何将包含对象数据的消息发送到 RabbitMQ 中,并在接收端处理对象数据:
发送端代码:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
public class RabbitMQSender {
private final static String QUEUE_NAME = "my_queue";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// Define your object
Person person = new Person("John", "Doe", 30);
// Convert the object to a byte array
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(person);
objOut.flush();
byte[] messageBodyBytes = byteOut.toByteArray();
// Publish the message to RabbitMQ
channel.basicPublish("", QUEUE_NAME, null, messageBodyBytes);
System.out.println(" [x] Sent object");
channel.close();
connection.close();
}
}
```
在这个示例中,我们定义了一个名为 Person 的对象,并使用 ObjectOutputStream 将其转换为字节数组。接下来,我们将字节数组作为消息体通过 RabbitMQ 发布到一个名为 "my_queue" 的队列中。您可以根据您的需求将队列名替换为您自己的队列名。
接收端代码:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
public class RabbitMQReceiver {
private final static String QUEUE_NAME = "my_queue";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
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) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
ByteArrayInputStream byteIn = new ByteArrayInputStream(body);
ObjectInputStream objIn = new ObjectInputStream(byteIn);
try {
Person person = (Person) objIn.readObject();
System.out.println(" [x] Received " + person);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
```
在接收端,我们使用 ObjectInputStream 将字节数组转换回对象,并在控制台上打印出该对象。这样,您就可以在 RabbitMQ 中发送和接收包含对象数据的消息了。请注意,您需要在发送方和接收方都包含 Person 类的定义。
阅读全文