猿问

如何将 XML 文件发送到 ActiveMQ?

在我的应用程序中,我使用 JAXB 将对象转换为 XML。我需要将此 XML 文件传输到 ActiveMQ 队列。以前我以这样的字符串形式将消息发送到队列:


public class Main {

    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

    private static String subject = "TestQueue";


    public static void main(String[] args) throws JMSException {

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        Connection connection = connectionFactory.createConnection();

        connection.start();


        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

        Destination destination = session.createQueue(subject);

        MessageProducer producer = session.createProducer(destination); 

        TextMessage message = session.createTextMessage("secondMessage ");

        producer.send(message);

        connection.close();

    }

}

但现在我需要传输 XML 文件。我怎样才能做到这一点?


胡子哥哥
浏览 176回答 1
1回答

交互式爱情

在 JMS(以及一般的消息传递)中,您发送的是消息而不是文件。您可以通过从文件中读取数据并将其放入 JMS 文本或字节消息中来将文件转换为消息。最简单的解决方案是这样的:public class Main {    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;    private static String subject = "TestQueue";    public static void main(String[] args) throws JMSException {        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);        Connection connection = connectionFactory.createConnection();        connection.start();        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);        Destination destination = session.createQueue(subject);        MessageProducer producer = session.createProducer(destination);         String xml = readXmlFromFile();        TextMessage message = session.createTextMessage(xml);        producer.send(message);        connection.close();    }    private static String readXmlFromFile() {        // read XML from file    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答