JMS / ActiveMQ: Sending an object with objects as

2019-08-27 11:29发布

问题:

I'm using ActiveMQ (with Spring) for sending messages to remote OSGi-Container. This works very fine, but there is one issue.

I got two classes implementing Serializable. One class is the class member of the other class, like this:

public class Member implements Serializble {
private int someValue;
private static final long serialVersionUID = -4329617004242031635L;
... }

public class Parent implements Serializable {
    private static final long serialVersionUID = -667242031635L;
private double otherValue;
private Member;
}

So, when is send a Parent instance, the Member of the Parent is null.

Hope you understand what my problem is :)

Edit: funny issue: I got a java.util.date in my class which is serialized correctly, but this is the only thing, all Doubles etc are null

回答1:

Serialized objects in byte messages are a bit hard to deal with.

I would go with object messages, as Aksel Willgert suggested, or simply take it to some more loosley coupled format, such as serialzied XML. I quick solution would be to use XStream to go to/from XML in a more loosely coupled fashion, a quick guide here: XStream

Update, and some code here (need to add xstream-.jar to your project)

// for all, instanciate XStream
XStream xstream = new XStream(new StaxDriver());

// Producer side:
TextMessage message = session.createTextMessage(xstream.toXML(mp));
producer.send(message);


// consumer side:
TextMessage tmsg = (TextMessage)msg;
Parent par = (Parent)xstream.fromXML(tmsg.getText());

par.getMember() // etc should work just fine.


回答2:

If Objects are an option, you might go for something like this

Producer side:

SomeObject someObject = new SomeObject();
ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setObject(someObject);
producer.send(objectMessage);

Consumer side:

private class MessageConsumer implements MessageListener {
    @Override
    public void onMessage(Message message) {
        logger.debug("onMessage() " + message);

        if (message instanceof ObjectMessage) {
            ObjectMessage objectMessage = (ObjectMessage) message;
            SomeObject someObject = (SomeObject)objectMessage.getObject();
        }
    }
}