Read Write BytesMessage JMS Example

Read Write BytesMessage JMS Example

Many types of messages you could send with JMS. In this example you will see how to send and read BytesMessage in JMS:

  • Write BytesMessage:
public void sendBytesMessage(String message) {
		
		try {
			
			logger.info("Sending message : {}", message);
			
			BytesMessage testMessage = session.createBytesMessage();
			testMessage.writeBytes(message.getBytes());
			testMessage.setJMSType("Java Honk type");
			producer.send(testMessage);
			
			logger.info("Message sent successfully : {}", message);
			
		} catch (Exception e) {
			logger.error("Error sending message to output queue name:{} --> details exceptions: --> ", SOLACE_OUTPUT_QUEUE_NAME, e);
		}
}
  • Read BytesMessage:
public void onMessage(Message testMessage) {

		try {
				BytesMessage bytesXMLMessage = ((BytesMessage) testMessage);
				byte[] b = new byte[(int) bytesXMLMessage.getBodyLength()];
				bytesXMLMessage.readBytes(b);
				//Print Message received as String
				logger.info("Message received:"+new String(b));
				//Get JMS type of message
				logger.info(bytesXMLMessage.getJMSType());
				testMessage.acknowledge();			
			
		} catch (JMSException e) {
			e.printStackTrace();
		}

}

For more information please visit Oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *