繁体   English   中英

使用Spring Boot JMS发送对象

[英]Sending object using 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对象(可序列化)外,我几乎会做同样的事情。 并且接收器类应该能够识别对象的类。

您可以直接创建一个ByteMessage并序列化您的对象(该对象必须可序列化):

    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
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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