简体   繁体   中英

Sending object using spring boot JMS

I made 2 classes : 1 to send and 1 to receive. Currently I can send just a basic string and it works well

Sender

@Component
public class Sender {

    @Autowired
    private JmsTemplate jmsTemplate;

    //Script must be serializable
    public void testSend(/*Script*/String message)
    {
        jmsTemplate.convertAndSend("my-destination", message);      
    }
}

Receiver

@Component
public class Receiver {

    @Autowired
    private ConfigurableApplicationContext context;

    @JmsListener(destination = "my-destination")
    public void receive(String message) {
        System.out.println(message);

        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        context.close();
    }
}

I can't implement proper code here, if someone can just show me how to do, I'd grateful

I would make almost the same thing but to send complex java objects (serializable). And the reeceiver class should be able to recognize the class of the object.

you can directly creates a ByteMessage and serialize your object in (the object have to be Serializable) :

    this.jmsTemplate.send("my-destination", new MessageCreator() {
        public Message createMessage(Session session) throws JMSException {
            final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            final ObjectOutputStream oOut = new ObjectOutputStream(bOut);
            oOut.writeObject(_object); // where object is the object to serialize
            bytes[] data = bOut.toByteArray();
            return session.createByteMessage(data);
        }
    });

and

    @JmsListener(destination = "my-destination")
    public void receive(Message message) {
        final BytesMessage message = (BytesMessage) _message;
        final byte[] array = new byte[Long.valueOf(message.getBodyLength()).intValue()];
        message.readBytes(array);
        final ByteArrayInputStream bIn = new ByteArrayInputStream(_bytes);
        final ObjectInputStream oIn = new ObjectInputStream(bIn);
        Object obj = oIn.readObject(); // the deserialized object
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM