JMS / ActiveMQ: Sending an object with objects as class members

狂风中的少年 提交于 2019-12-13 05:50:34

问题


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();
        }
    }
}


来源:https://stackoverflow.com/questions/13307207/jms-activemq-sending-an-object-with-objects-as-class-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!