如何创建JSON类型的JMS消息?能否通过读取JSON文件实现?
Absolutely! Reading a JSON file to build and send JMS messages is a fantastic workaround for avoiding the headache of manually setting dozens of properties. Let’s break down how to do this with both vanilla JMS and Spring JMS—two of the most common setups for JMS messaging.
This approach works for standard JMS implementations without Spring dependencies.
Step 1: Prepare Your JSON Test File
First, create a JSON file (e.g., test-jms-message.json) with your full message content. If you need JMS-specific properties, you can even include them in the file and parse them later:
{ "jmsProperties": { "messageType": "ORDER_CONFIRMATION", "priority": "HIGH" }, "messageBody": { "orderId": "ORD-78901", "customer": { "name": "Megan Smith", "email": "megan@example.com" }, "items": [ {"sku": "PROD-456", "quantity": 3}, {"sku": "PROD-789", "quantity": 1} ] } }
Step 2: Read the File & Send the Message
Use standard Java I/O to read the file, parse the JSON, and construct your JMS message. Here’s a complete example with ActiveMQ:
import javax.jms.*; import org.apache.activemq.ActiveMQConnectionFactory; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.nio.file.Files; import java.nio.file.Paths; public class JsonJmsSender { public static void main(String[] args) throws Exception { // 1. Initialize JMS connection & resources String brokerUrl = "tcp://localhost:61616"; ConnectionFactory factory = new ActiveMQConnectionFactory(brokerUrl); Connection connection = factory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination queue = session.createQueue("test-order-queue"); MessageProducer producer = session.createProducer(queue); // 2. Read and parse the JSON file String jsonContent = new String(Files.readAllBytes(Paths.get("test-jms-message.json"))); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(jsonContent); // 3. Create JMS TextMessage with the body content TextMessage message = session.createTextMessage(rootNode.get("messageBody").toString()); // 4. Set JMS properties from the JSON file JsonNode propertiesNode = rootNode.get("jmsProperties"); propertiesNode.fields().forEachRemaining(entry -> { try { message.setStringProperty(entry.getKey(), entry.getValue().asText()); } catch (JMSException e) { e.printStackTrace(); } }); // 5. Send the message producer.send(message); System.out.println("JSON-based JMS message sent successfully!"); // 6. Clean up resources producer.close(); session.close(); connection.close(); } }
If you’re working in a Spring ecosystem, JmsTemplate makes this even cleaner—no manual resource management needed.
Step 1: Same JSON File as Above
Reuse the test-jms-message.json file from the vanilla JMS example.
Step 2: Implement the Sender
Use Spring’s file utilities and JmsTemplate to read and send the message:
import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import javax.jms.TextMessage; import java.io.FileReader; @Component public class SpringJsonJmsSender { private final JmsTemplate jmsTemplate; private final ObjectMapper objectMapper; // Constructor injection (Spring handles bean wiring) public SpringJsonJmsSender(JmsTemplate jmsTemplate, ObjectMapper objectMapper) { this.jmsTemplate = jmsTemplate; this.objectMapper = objectMapper; } public void sendJsonMessage(String filePath, String queueName) throws Exception { // Read JSON file content String jsonContent = FileCopyUtils.copyToString(new FileReader(filePath)); JsonNode rootNode = objectMapper.readTree(jsonContent); // Send message via JmsTemplate jmsTemplate.send(queueName, session -> { TextMessage message = session.createTextMessage(rootNode.get("messageBody").toString()); // Set JMS properties JsonNode properties = rootNode.get("jmsProperties"); properties.fields().forEachRemaining(entry -> { try { message.setStringProperty(entry.getKey(), entry.getValue().asText()); } catch (JMSException e) { throw new RuntimeException("Failed to set JMS property", e); } }); return message; }); } }
- Batch Testing: Loop through a directory of JSON files to send multiple test messages in one go.
- Skip Object Parsing: If you don’t need to modify the message or set properties, you can send the raw JSON string directly as a
TextMessagewithout parsing it first—saves time for simple tests. - Externalize Config: Store broker URLs and queue names in a properties file instead of hardcoding them, making your sender reusable across environments.
内容的提问来源于stack exchange,提问作者Megan

