JAVA操作IBM MQ

Wesley13
• 阅读 496

java往MQ里面发消息和取消息

package test;
    import java.io.IOException;   

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.constants.MQConstants;
      
    public class test1{   
         //定义队列管理器和队列的名称   
     private static String qmName;    
     private static String qName;   
     private static MQQueueManager qMgr;   
     static{   
         //设置环境:   
             //MQEnvironment中包含控制MQQueueManager对象中的环境的构成的静态变量,MQEnvironment的值的设定会在MQQueueManager的构造函数加载的时候起作用,   
             //因此必须在建立MQQueueManager对象之前设定MQEnvironment中的值.   
         MQEnvironment.hostname="172.31.17.162";          //MQ服务器的IP地址         
         MQEnvironment.channel="SVRCONN_GW";              //服务器连接的通道   
         MQEnvironment.CCSID=1208;                      //服务器MQ服务使用的编码1381代表GBK、1208代表UTF(Coded Character Set Identifier:CCSID)   
         MQEnvironment.port=33333;                       //MQ端口   
         qmName = "QM_TEST";                          //MQ的队列管理器名称   
         qName = "TEST";                               //MQ远程队列的名称   
         try {   
             //定义并初始化队列管理器对象并连接    
             //MQQueueManager可以被多线程共享,但是从MQ获取信息的时候是同步的,任何时候只有一个线程可以和MQ通信。   
            qMgr = new MQQueueManager(qmName);   
        } catch (MQException e) {   
                // TODO Auto-generated catch block   
                System.out.println("初使化MQ出错");   
                e.printStackTrace();   
        }    
         }   
         /**  
      * 往MQ发送消息  
      * @param message  
          * @return  
      */  
     public static int sendMessage(String message){   
         int result=0;   
         try{      
             //设置将要连接的队列属性   
                 // Note. The MQC interface defines all the constants used by the WebSphere MQ Java programming interface    
                 //(except for completion code constants and error code constants).   
                 //MQOO_INPUT_AS_Q_DEF:Open the queue to get messages using the queue-defined default.   
             //MQOO_OUTPUT:Open the queue to put messages.   
             /*目标为远程队列,所有这里不可以用MQOO_INPUT_AS_Q_DEF属性*/  
             //int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;   
                 /*以下选项可适合远程队列与本地队列*/  
             int openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING;   
                 //连接队列    
             //MQQueue provides inquire, set, put and get operations for WebSphere MQ queues.    
             //The inquire and set capabilities are inherited from MQManagedObject.    
             /*关闭了就重新打开*/  
            if(qMgr==null || !qMgr.isConnected()){   
                qMgr = new MQQueueManager(qmName);   
                }   
             MQQueue queue = qMgr.accessQueue(qName, openOptions);             
             //定义一个简单的消息   
             MQMessage putMessage = new MQMessage();    
             //将数据放入消息缓冲区   
             putMessage.writeUTF(message);     
             //设置写入消息的属性(默认属性)   
             MQPutMessageOptions pmo = new MQPutMessageOptions();              
             //将消息写入队列    
             queue.put(putMessage,pmo);    
             queue.close();   
         }catch (MQException ex) {    
             System.out.println("A WebSphere MQ error occurred : Completion code "    
             + ex.completionCode + " Reason code " + ex.reasonCode);    
             ex.printStackTrace();   
         }catch (IOException ex) {    
             System.out.println("An error occurred whilst writing to the message buffer: " + ex);    
         }catch(Exception ex){   
             ex.printStackTrace();   
         }finally{   
             try {   
                    qMgr.disconnect();   
            } catch (MQException e) {   
                e.printStackTrace();   
            }   
         }   
        return result;   
     }   
     /**  
      * 从队列中去获取消息,如果队列中没有消息,就会发生异常,不过没有关系,有TRY...CATCH,如果是第三方程序调用方法,如果无返回则说明无消息  
      * 第三方可以将该方法放于一个无限循环的while(true){...}之中,不需要设置等待,因为在该方法内部在没有消息的时候会自动等待。  
      * @return  
      */  
     public static String getMessage(){   
         String message=null;   
         try{               
                 //设置将要连接的队列属性   
                 // Note. The MQC interface defines all the constants used by the WebSphere MQ Java programming interface    
                 //(except for completion code constants and error code constants).   
                 //MQOO_INPUT_AS_Q_DEF:Open the queue to get messages using the queue-defined default.   
                 //MQOO_OUTPUT:Open the queue to put messages.   
                 int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;   
                 MQMessage retrieve = new MQMessage();   
                 //设置取出消息的属性(默认属性)   
                 //Set the put message options.(设置放置消息选项)    
                 MQGetMessageOptions gmo = new MQGetMessageOptions();    
             gmo.options = gmo.options + MQC.MQGMO_SYNCPOINT;//Get messages under sync point control(在同步点控制下获取消息)    
                 gmo.options = gmo.options + MQC.MQGMO_WAIT;  // Wait if no messages on the Queue(如果在队列上没有消息则等待)    
                 gmo.options = gmo.options + MQC.MQGMO_FAIL_IF_QUIESCING;// Fail if Qeue Manager Quiescing(如果队列管理器停顿则失败)    
                 gmo.waitInterval = 1000 ;  // Sets the time limit for the wait.(设置等待的毫秒时间限制)    
                 /*关闭了就重新打开*/  
                if(qMgr==null || !qMgr.isConnected()){   
                    qMgr = new MQQueueManager(qmName);   
                }   
                 MQQueue queue = qMgr.accessQueue(qName, openOptions);    
                 // 从队列中取出消息   
                 queue.get(retrieve, gmo);
                 byte[] buf = new byte[retrieve.getMessageLength()];
                 retrieve.readFully(buf);
                     
                 System.out.println("The message is: " + new String(buf));    
                 queue.close();   
             }catch (MQException ex) {    
                 System.out.println("A WebSphere MQ error occurred : Completion code "    
                 + ex.completionCode + " Reason code " + ex.reasonCode);    
             }catch (IOException ex) {    
                 System.out.println("An error occurred whilst writing to the message buffer: " + ex);    
             }catch(Exception ex){   
                 ex.printStackTrace();   
             }finally{   
                 try {   
                    qMgr.disconnect();   
                } catch (MQException e) 
                {                       e.printStackTrace();   
                }   
             }   
             return message;   
         }   
         public static void main(String args[]) throws InterruptedException {   
             /*下面两个方法可同时使用,也可以单独使用*/  
             //sendMessage("this is a test");
             //System.out.println("jwh");
             for (int i = 0; i < 100; i++) {
                 getMessage();
                 Thread.sleep(20000);
            }
               
             
             
         }   
    }  
    *
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Nginx + lua +[memcached,redis]
精品案例1、Nginxluamemcached,redis实现网站灰度发布2、分库分表/基于Leaf组件实现的全球唯一ID(非UUID)3、Redis独立数据监控,实现订单超时操作/MQ死信操作SelectPollEpollReactor模型4、分布式任务调试Quartz应用
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
Docker 部署SpringBoot项目不香吗?
  公众号改版后文章乱序推荐,希望你可以点击上方“Java进阶架构师”,点击右上角,将我们设为★“星标”!这样才不会错过每日进阶架构文章呀。  !(http://dingyue.ws.126.net/2020/0920/b00fbfc7j00qgy5xy002kd200qo00hsg00it00cj.jpg)  2
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这