I am using IBM MQ as my queue service.
How to write text message into IBM MQ by Java?
How-To
Here has sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | package com.xxx.mql.service; import java.io.IOException; import java.util.Enumeration; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueBrowser; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.commons.lang.StringUtils; import com.ibm.mq.jms.MQQueueConnection; import com.ibm.mq.jms.MQQueueConnectionFactory; import com.ibm.mq.jms.MQQueueReceiver; import com.ibm.mq.jms.MQQueueSender; import com.ibm.mq.jms.MQQueueSession; import com.tdcc.mql.enumeration.MQParamKeyType; import com.tdcc.mql.utils.MqlUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class TestMQService { private static TestMQService mqServuce; private static String mqHost = MQParamKeyType.MQ_HOST.getSystemValue(); private static String mqChannel = MQParamKeyType.MQ_CHANNEL.getSystemValue(); private static String mqUser = MQParamKeyType.MQ_USER.getSystemValue(); private static String mqPwd = MQParamKeyType.MQ_PASSWORD.getSystemValue(); private static String mqQueueMgr = MQParamKeyType.MQ_QUEUEMGR.getSystemValue(); private static String mqPort = MQParamKeyType.MQ_PORT.getSystemValue(); public static TestMQService getInstance() { if (mqServuce == null) { mqServuce = new TestMQService(); return mqServuce; } else { return mqServuce; } } /** * Send Message to MQ. * * @param queueName * @param message * @throws JMSException */ public void writeMessageToMQ(String queueName, String message) throws JMSException { MQQueueConnectionFactory connFactory = new MQQueueConnectionFactory(); MQQueueSender sender = null; MQQueueSession session = null; MQQueueConnection connection = null; try { connFactory.setHostName(mqHost); connFactory.setPort(Integer.parseInt(mqPort)); connFactory.setTransportType(1); connFactory.setQueueManager(mqQueueMgr); connFactory.setChannel(mqChannel); connection = (MQQueueConnection) connFactory.createQueueConnection(); session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); sender = (MQQueueSender) session.createSender(queue); connection.start(); TextMessage textMsg = session.createTextMessage(); textMsg.setText(message); sender.send(textMsg); } catch (JMSException e) { log.error(MqlUtils.toStackTrace(e)); } finally { if (sender != null) { sender.close(); } if (session != null) { session.close(); } if (connection != null) { connection.close(); } } } } |