您好我是RabbitMQ的新手,我正在尝试在两个应用程序之间发送一个对象,但是它不起作用我然后发现我需要序列化和反序列化对象但它仍然无法正常工作。当我发送一个字符串时没有问题,但是对于突然没有工作的对象,应用程序之间没有连接,我不确定我做错了什么。
这是Sender.java:
import org.apache.commons.lang3.SerializationUtils;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class App {
private final static String QUEUE_NAME = "12345";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("somehost");
factory.setUsername("guest");
// factory.setPassword( "password" );
//factory.setPort( 12345 );
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
Car car = new Car(4, 4, "Mercedes");
byte[] data = SerializationUtils.serialize(car);
channel.basicPublish("", QUEUE_NAME, null, data);
System.out.println(" [x] Sent '" + data + "'");
channel.close();
connection.close();
}
}
这是Receiver.java:
import org.apache.commons.lang3.SerializationUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Recipient {
private final static String QUEUE_NAME = "12345";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("Somehost");
factory.setUsername("guest");
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");
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
//byte [] data = new byte[];
Object object = SerializationUtils.deserialize(message.getBytes());
System.out.println(" [x] Received '" + object + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
//byte [] data = new byte[];
Object object = SerializationUtils.deserialize(body);
System.out.println(" [x] Received '" + object + "'");
}
};
只需直接从body
变量反序列化