java 语言 实现rabbitMQ 发送LIST对象数据
时间: 2024-02-11 18:06:23 浏览: 28
在 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.util.ArrayList;
import java.util.List;
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 list object
List<String> myList = new ArrayList<>();
myList.add("Hello");
myList.add("World");
// Convert the list object to a byte array
byte[] messageBodyBytes = SerializationUtils.serialize(myList);
// Publish the message to RabbitMQ
channel.basicPublish("", QUEUE_NAME, null, messageBodyBytes);
System.out.println(" [x] Sent list object");
channel.close();
connection.close();
}
}
```
在这个示例中,我们使用了 Apache Commons Lang 库的 SerializationUtils 类将列表对象转换为字节数组。接下来,我们将字节数组作为消息体通过 RabbitMQ 发布到一个名为 "my_queue" 的队列中。您可以根据您的需求将队列名替换为您自己的队列名。请注意,您需要在发送方和接收方都包含 SerializationUtils 类的依赖项。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)