5

您好,我是 RabbitMQ 的新手,我正在尝试在 2 个应用程序之间发送一个对象,但它不起作用然后我发现我需要序列化和反序列化这些对象,但它仍然不起作用。当我发送字符串时没有问题,但是对象突然无法正常工作,应用程序之间没有连接,我不确定我做错了什么。

这是 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);
     }
    }
4

1 回答 1

1
@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变量反序列化

于 2017-12-24T19:35:59.807 回答