2017-10-06 140 views
0

你好我是新來的RabbitMQ,我想在2個應用程序之間發送一個對象,但它不工作然後我發現我需要序列化和反序列化對象,但它仍然不工作。當我發送一個字符串時沒有問題,但是對象沒有突然工作,應用程序之間沒有連接,我不知道我做錯了什麼。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); 
    } 
    } 
+0

什麼做反序列化你m是否應用程序之間沒有聯繫?你如何檢查它?你在看管理屏幕嗎?如果你沒有檢查它,我會建議在handleDelivery方法的頂部添加一個System.out.println,看看它是否到達 –

+0

任何可以提供幫助的人? –

回答

0
@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變量