使用spring boot JMS发送对象

时间:2016-01-15 10:09:44

标签: java spring spring-boot jms

我做了2个课程:1个发送,1个接收。目前我只能发送一个基本的字符串,它运作良好

发件人

@Component
public class Sender {

    @Autowired
    private JmsTemplate jmsTemplate;

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

接收机

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

我无法在此处实施正确的代码,如果有人可以告诉我该怎么做,我很感激

我会发送几乎相同的东西,但发送复杂的java对象(可序列化)。并且reeceiver类应该能够识别对象的类。

1 个答案:

答案 0 :(得分:1)

你可以直接创建一个ByteMessage并序列化你的对象(该对象必须是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);
        }
    });

    @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
    }