jmeter創建自定義java sampler往IBM MQ中發送消息的步驟


最近做的一個項目需要往IBM的MQ隊列中發送消息由於jmeter沒有這種Sampler所以就自己動手打造一個,記錄步驟

步驟為:

  1. 下載需要的jar包
  2. 新建一個Java項目
  3. 導入jar包
  4. 編寫sampler代碼
  5. 將項目導出成jar包
  6. 將jar包放入{jmeterhome}/lib/ext
  7. 打開jmeter GUI新建一個java Sampler選擇需要的請求類型即可

 

以下為詳細步驟說明

1. 下載IBM MQ jar包,地址:https://repo1.maven.org/maven2/com/ibm/mq/com.ibm.mq.allclient/9.1.4.0/

還需要jmeter的jar包可在{jmeterhome}/lib/ext中找到

 

 

 

2.新建java項目一直下一步就行

 

 

 

3.點擊file->project Structure將需要的包都導入

 

 

 

 

4.新建一個Java類繼承 AbstractJavaSamplerClient 直接看源碼吧

package com.ms.ibmmqsampler;

import com.ibm.mq.*;
import com.ibm.mq.constants.CMQC;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.util.Arrays;
import java.util.Properties;

public class SendMsg extends AbstractJavaSamplerClient {
    private static final int CCSID = 1208;
    private static MQQueueManager qMgr;
    private static String queueString;

    /**
     * 通過getDefaultParameters()定義入參
     */
    @Override
    public Arguments getDefaultParameters() {
        //定義屬性對象,用來添加GUI參數
        Arguments params = new Arguments();
        //添加一個GUI參數,名稱叫"method",值是"add"
        params.addArgument("hostname", "127.0.0.1");
        params.addArgument("port", "1819");
        params.addArgument("userID", "mqm");
        params.addArgument("password", "mqm");
        params.addArgument("channel", "SYSTEM.DEF.SVRCONN");
        params.addArgument("CCSID", "1208");
        params.addArgument("queueString", "RECV.QUEUE");
        params.addArgument("QueueManagerName", "QM1");
        return params;
    }

    //每個線程測試前執行一次,做一些初始化工作;
    @Override
    public void setupTest(JavaSamplerContext arg0) {
        Properties props = new Properties();
        props.put("hostname", arg0.getParameter("hostname"));
        props.put("port", arg0.getParameter("port"));
        props.put("channel", arg0.getParameter("channel"));
        props.put("CCSID", arg0.getParameter("CCSID"));
        props.put("userID", arg0.getParameter("userID"));
        props.put("password", arg0.getParameter("password"));

        queueString = arg0.getParameter("queueString");
        try {
            qMgr = new MQQueueManager(arg0.getParameter("QueueManagerName"), props);
        } catch (MQException e) {
            e.printStackTrace();
        }
    }

    //JavaSampleContext arg0()就是用來接收GUI所提交的
    @Override
    public SampleResult runTest(JavaSamplerContext arg0) {
        // TODO Auto-generated method stub
        SampleResult sr = new SampleResult();
        try {
            //將GUI界面傳遞過來的值賦給全局變量
//            method = arg0.getParameter("method");
//            x = Integer.parseInt(arg0.getParameter("num1", null));
//            y = Integer.parseInt(arg0.getParameter("num2", null));
            //是表示請求開始計時
            sr.sampleStart();
            //實際測試不需要,模擬處理過程中所需消耗的時間
            // Random rnd = new Random();
            // Thread.sleep(rnd.nextInt(1000));
            //通過GUI傳遞的method參數來決定所執行的方法

            //qMgr = new MQQueueManager("QM1");
            byte[] b = hexStringToBytes("39303031303330353230313930333133313931343539313833303133373932343820202020202020202031303030303030303030303030304334323138373130303030303030353930202020202020202000202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202030323130F23E40818EC0801000000000100000013136343231383731303030303030303030303035393030303030303030303030313030303033313331393135313430363532353931353230333630333137303030302020202037303131303030383033303530303031303830303031303334343033303930303030373232383539373831333030313233343536373831323334353637383930313233343531536303330303030303032303030333030303020202020202020202020202020343030303830333035303030314544414642413736");
            System.out.println("senMsg: " + Arrays.toString(b));
            sendMsg(b);

//            receiveMsg();

//            if (method.equals("add")) {
//                resultData = String.valueOf(c.add(x, y));
//            } else if (method.equals("minus")) {
//                resultData = String.valueOf(c.minus(x, y));
//            }
//            if (resultData != null && resultData.length() > 0) {
            //設置響應數據為resutlData;也可以用sr.setSamplerData("OK");
            sr.setResponseData(Arrays.toString(b), null);
            //設置響應代碼為0000
            sr.setResponseCode("0000");
            //設置響應類型為text
            sr.setContentType(SampleResult.TEXT);
            //設置響應狀態為true
            sr.setSuccessful(true);
            //設置響應信息
            sr.setResponseMessage("方法執行成功!");
//            } else {
//                sr.setResponseData(resultData, null);
//                //設置響應代碼為-9999
//                sr.setResponseCode("-9999");
//                //設置響應類型為txt
//                sr.setContentType(SampleResult.TEXT);
//                //設置響應狀態為true
//                sr.setSuccessful(false);
//                //設置響應信息
//                sr.setResponseMessage("方法執行失敗!");
//            }

        } catch (Exception e) {
            sr.setResponseData(e.getMessage(), null);
            e.printStackTrace();
            sr.setResponseCode("-1");
            sr.setContentType(SampleResult.TEXT);
            sr.setSuccessful(false);
            sr.setResponseMessage("捕獲異常!");
        } finally {
            //表示請求結束計時
            sr.sampleEnd();
        }
        //表示返回這個SampleResult對象sr
        return sr;
    }

    @Override
    public void teardownTest(JavaSamplerContext arg0) {
//         System.out.println(end);
//         System.out.println("The cost is"+(end-start)/1000);
    }

    private static void sendMsg(byte[] b) {
        int openOptions = CMQC.MQOO_INPUT_AS_Q_DEF | CMQC.MQOO_OUTPUT | CMQC.MQOO_INQUIRE;
        MQQueue queue = null;
        try {
            queue = qMgr.accessQueue(queueString, openOptions, null, null, null);
            MQMessage msg = new MQMessage();
            msg.characterSet = CCSID;
            msg.encoding = CCSID;
            msg.write(b);
            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();
                }
            }
        }
    }

    private void sendTopic() {
        try {
            MQEnvironment.properties.put(CMQC.TRANSPORT_PROPERTY,
                    CMQC.TRANSPORT_MQSERIES);
            MQTopic topic = qMgr.accessTopic("TOPIC_xx_2", "TOPIC_xx_2", CMQC.MQTOPIC_OPEN_AS_PUBLICATION, CMQC.MQOO_OUTPUT);
            MQPutMessageOptions option = new MQPutMessageOptions();
            option.options = CMQC.MQPMO_FAIL_IF_QUIESCING | CMQC.MQPMO_RETAIN;
            ;
            MQMessage msg = new MQMessage();
            msg.expiry = 5 * 60 * 1000;
            msg.writeObject("test");
            msg.setStringProperty("test", "1");
            topic.put(msg, option);
            qMgr.commit();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private void receiveTopic() {
        try {
            MQEnvironment.properties.put(CMQC.TRANSPORT_PROPERTY,
                    CMQC.TRANSPORT_MQSERIES);
            MQTopic topic = qMgr.accessTopic("TOPIC_xx_2", "TOPIC_xx_2", CMQC.MQTOPIC_OPEN_AS_SUBSCRIPTION, CMQC.MQSO_CREATE);
            MQMessage msg = new MQMessage();
            MQGetMessageOptions option = new MQGetMessageOptions();
            topic.get(msg, option);
            qMgr.commit();
            System.out.println(msg.getStringProperty("test"));
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    private static void receiveMsg() {
        int openOptions = CMQC.MQOO_INPUT_AS_Q_DEF | CMQC.MQOO_OUTPUT | CMQC.MQOO_INQUIRE;
        MQQueue queue = null;
        try {
            queue = qMgr.accessQueue(queueString, openOptions, null, null, null);
            System.out.println("CurrentDepth: " + 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("DataLength: " + msg.getDataLength());
                byte[] rawData = new byte[msg.getMessageLength()];
                msg.readFully(rawData);
                String msgs = printHexString(rawData);
                System.out.println(Arrays.toString(rawData));
                System.out.println(msgs);
                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();
                }
            }
        }
    }

    private static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringb = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringb.append(0);
            }
            stringb.append(hv);
        }
        return stringb.toString();
    }

    private static String printHexString(byte[] b) {
        String a = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            a = a + hex;
        }
        return a;
    }

//    public static void main(String[] args) {
////        // 設置參數,並賦予默認值1
////        params.addArgument("num1", "1");
////        params.addArgument("num2", "2");
//        SendMsg test = new SendMsg();
//        Arguments params = test.getDefaultParameters();
//        JavaSamplerContext arg0 = new JavaSamplerContext(params);
//        test.setupTest(arg0);
//        test.runTest(arg0);
//        test.teardownTest(arg0);
//    }
}


5.將項目導出成jar包 點擊file->project Structure選擇Artifacts

 

 

 

 

 

 

 

 

 

 

將jar包放入{jmeterhome}/lib/ext后打開jmeter

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM