Java连接MQ的实例
2015-07-13 20:10
585 查看
package cjf.mq.mqclient; import com.ibm.mq.MQC; import com.ibm.mq.MQEnvironment; import com.ibm.mq.MQException; import com.ibm.mq.MQGetMessageOptions; import com.ibm.mq.MQMessage; import com.ibm.mq.MQPutMessageOptions; import com.ibm.mq.MQQueue; import com.ibm.mq.MQQueueManager; import com.ibm.mq.MQGetMessageOptions; public class MQClient { static MQQueueManager qMgr; static int CCSID = 1381;//WINGBK,1208:UTF-8 static String queueString = "MQ_QUEUE"; public static void connect() throws MQException { MQEnvironment.hostname = ""; MQEnvironment.channel = "java.channel"; MQEnvironment.port = 1321; MQEnvironment.CCSID = CCSID; qMgr = new MQQueueManager("MQ_TEST"); qMgr.disconnect(); } public static void sendMsg(String msgStr) { int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE; MQQueue queue = null; try { // 建立Q1通道的连接 queue = qMgr .accessQueue(queueString, openOptions, null, null, null); MQMessage msg = new MQMessage();// 要写入队列的消息 msg.format = MQC.MQFMT_STRING; msg.characterSet = CCSID; msg.encoding = CCSID; // msg.writeObject(msgStr); //将消息写入消息对象中 msg.writeString(msgStr); MQPutMessageOptions pmo = new MQPutMessageOptions(); msg.expiry = -1; // 设置消息用不过期 queue.put(msg, pmo);// 将消息放入队列 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (queue != null) { try { queue.close(); } catch (MQException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void receiveMsg() { int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE; MQQueue queue = null; try { queue = qMgr .accessQueue(queueString, openOptions, null, null, null); System.out.println("该队列当前的深度为:" + queue.getCurrentDepth()); System.out.println("==========================="); int depth = queue.getCurrentDepth(); // 将队列的里的消息读出来 while (depth-- > 0) { MQMessage msg = new MQMessage();// 要读的队列的消息 MQGetMessageOptions gmo = new MQGetMessageOptions(); queue.get(msg, gmo); System.out.println("消息的大小为:" + msg.getDataLength()); System.out.println("消息的内容:\n" + msg.readLine()); System.out.println("---------------------------"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (queue != null) { try { queue.close(); } catch (MQException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args) throws MQException { connect(); sendMsg("fuck MQ"); receiveMsg(); } }
相关文章推荐
- springmvc拦截器使用
- 通过JAVA从MQ读取消息的时候报错及解决
- 与MQ通讯的完整JAVA程序
- wsdl2java在mac中点配置
- 关于Eclipse的SVN插件(Subclipse)历史版本乱码的问题
- eclipse中出现"确认切换透视图“的原因
- Java继承关系与接口
- Java集合之HashSet源码分析
- Java调用MQ队列
- java io
- websphere MQ 编程指南(Java)
- java中Date的getTime()函数
- Rabbitmq-Java-Client重连和consumer恢复机制
- Java中map学习笔记(一)
- java实现顺序链表
- java学习之旅61--数组_多维数组_练习_矩阵运算
- 【leetcode-90】SubsetII(java 语言)
- Java-异常总结
- java 基础知识及Servlet基础
- 网易云课堂-Java语言程序设计进阶-第一次测试答案