與MQ通訊的完整JAVA程式

來源:互聯網
上載者:User

標籤:des   blog   http   java   使用   os   io   資料   

該程式實現了發送訊息與讀取訊息的功能,見其中的 send***與get***方法。這隻適合於測試,因為環境中的程式還需要對此有稍微的更改,在真實的環境中肯定是在while(true){...} 的無限迴圈中去調用其中的get方法,如果有值,那就執行對訊息的處理操作,如果沒有值就繼續迴圈,在get方法中有等待的時間。

這個程式就其本身來說還是比較理解的:

1、首先設定一些相關的環境變數

2、再串連隊列管理器

3、再次操作隊列管理器中的指定隊列

4、往指定隊列中發訊息或者是從指定對列中取訊息

5、關閉隊列

如果不知道如何在MQ資源管理員中配置遠程隊列及通過遠程隊列往遠端MQ發送訊息,請參見文章:

http://blog.csdn.net/fenglibing/archive/2009/05/08/4160639.aspx

真 實環境中的MQ,個人覺得至少都應該有兩個本地隊列加一個遠程隊列,因為訊息的互動肯定是相互的,有收訊息,肯定也有發訊息。一個本地隊列用於接收外部發 過來的訊息,用法為正常;另一個本地隊例用於傳輸,用於做於遠程隊例的傳輸隊列,將訊息發送給遠程主機的本地隊列。要使訊息能夠成功的傳送到遠程隊列,還 需要配置通道,通常中需要指定遠程通道的IP地址及連接埠、本地傳輸隊例的名稱、以及本地的通訊地址,這樣才能夠往遠程主機發送訊息。

view plaincopy to clipboardprint?
/** 
 * @author Fenglb E-mail:[email protected] 
 * @version 建立時間:2009-4-30 下午04:13:38 
 * 類說明 
 */ 
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;  
 
public class MessageByMQ{  
     //定義隊列管理器和隊列的名稱  
     private static String qmName;   
     private static String qName;  
     private static MQQueueManager qMgr;  
     static{  
         //設定環境:  
         //MQEnvironment中包含控制MQQueueManager對象中的環境的構成的靜態變數,MQEnvironment的值的設定會在MQQueueManager的建構函式載入的時候起作用,  
         //因此必須在建立MQQueueManager對象之前設定MQEnvironment中的值.  
         MQEnvironment.hostname="10.24.1.180";          //MQ伺服器的IP地址        
         MQEnvironment.channel="S_FENGLB";              //伺服器串連的通道  
         MQEnvironment.CCSID=1381;                      //伺服器MQ服務使用的編碼1381代表GBK、1208代表UTF(Coded Character Set Identifier:CCSID)  
         MQEnvironment.port=1414;                       //MQ連接埠  
         qmName = "QM_FENGLB";                          //MQ的隊列管理器名稱  
         qName = "testQ";                               //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);  
             message = retrieve.readUTF();    
             System.out.println("The message is: " + message);   
             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[]) {  
         /*下面兩個方法可同時使用,也可以單獨使用*/ 
         sendMessage("this is a test");  
         //getMessage();  
     }  

 

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/fenglibing/archive/2009/05/08/4161441.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.