jmeter dubbo插件源代码+思路

本文主要介绍JMeter Dubbo插件的源代码,并讨论如何根据不同的接口参数类型进行修改。博客提供了核心代码示例,包括Dubbo配置、接口调用和JSON处理,以适应不同公司的业务需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 这个blog主要是解决上传的资料jmeter-dubbo的里面源代码,

2.由于各个公司业务不尽相同,因此接口参数类型也不一定相同,譬如我们的接口就有类似如 Interger | Interger,  String | Interger,之类,故而可能需要修改源代码。

核心代码:



import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
import org.apache.commons.lang3.StringUtils;
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 org.apache.log.Logger;


import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


public class DubboJmeterTest extends AbstractJavaSamplerClient {


    private Logger logger = getLogger();


    private String protocol;
    private String address;
    private String client;
    private int timeout;
    private String serviceInterfaceName;
    private String serviceMethod;
    private String serviceInputDto;
    private String serviceVersion;
    private String params;
    private ReferenceConfig<GenericService> reference;
    private ReferenceConfigCache cache;
    private long start = 0;//
    private long end = 0;//


    public static boolean isJson(String json) throws Exception {
        try {
            JSON.parse(json);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static void main(String[] args) throws Exception {
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("zookeeper");
        registry.setAddress("192.168.30.1:2181");
        registry.setClient("curator");
        registry.setTimeout(5000);


        UniqueServiceDefined usd = new UniqueServiceDefined();

        //待测接口

        usd.setServiceInterfaceName("com.test.Facade");

       //待测方法

        usd.setServiceMethod("getDate");
        usd.setServiceInputDto("");
        usd.setServiceVersion("4.0.0");


        //String params = "{\"pageSize\":\"2\",\"pageNum\":\"1\"}||{\"mid\": \"1820150000001395\"}";
        //String params = "{\"pageSize\":\"2\",\"pageNum\":\"1\"}||{\"mid\": \"1820150000001395\",\"lid\":\"2200000005669025\",\"fid\":\"0\",\"ctId\":\"0\"}";
        //String params="{\"mid\": \"1820150000001395\"}";
        //String params = "1 || {\"orderClause\":\"desc\",\"rownum\":\"1\",\"time\":\"2017-06-19 15:00:00\",\"groupBy\":\"id\"}";
        //String params="[{\"MbId\":\"123\",\"AlId\":\"1\",\"Minrate\":\"1\",\"Maxrate\":\"11\",\"Minamount\":\"2\",\"Maxamount\":\"22\",\"Mindeadline\":\"2\",\"Maxdeadline\":\"1\",\"Bidamount\":\"1\",\"Status\":\"0\",\"Bidamountflag\":\"1\",\"Transfer\":\"1\",\"LoanCategoryId\":\"12\",\"ActiveBidAmount\":\"0\",\"LoanCategoryIdList\":[1,3]}]";
        String params="";
        if (StringUtils.isEmpty(params)) {
            System.out.println("such a fool of you");
        }
        String result = new DubboJmeterTest().call(registry, usd, params);
        System.out.println(result);
        System.exit(0);
    }


    /**
     * dubbo
     *
     * @param registry
     * @param uniqueServiceDefined
     * @param params
     * @return
     */
    public String call(RegistryConfig registry, UniqueServiceDefined uniqueServiceDefined, String params) throws Exception {
        ApplicationConfig application = new ApplicationConfig();
        application.setName("dubbo-test");
        reference = new ReferenceConfig<GenericService>();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setInterface(uniqueServiceDefined.getServiceInterfaceName()); // 
        reference.setGeneric(true);
        reference.setCheck(false);
        reference.setVersion(uniqueServiceDefined.getServiceVersion());

        cache = ReferenceConfigCache.getCache();


        long beforeTime = System.currentTimeMillis();
        GenericService genericService = cache.get(reference);
        long endTime = System.currentTimeMillis();
        logger.info("{" + uniqueServiceDefined.getServiceInterfaceName() + "},{" + (endTime - beforeTime) + "}");
        String[] paramsstr = params.split("\\|\\|");
        String[] inputtype = uniqueServiceDefined.getServiceInputDto().split("\\|\\|");
        Object[] inputvalue = null;
        if (StringUtils.isEmpty(params)) {
        }
        if (!StringUtils.isEmpty(params)) {
            inputvalue = new Object[paramsstr.length];
            for (int i = 0; i < paramsstr.length; i++) {
                if (isJson(paramsstr[i])) {
                    Map<?, ?> m = GsonUtil.fromJson(paramsstr[i], Map.class);
                    if (m == null || m.size() < 1) {
                        if (inputtype[i].equals("java.lang.Long")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    long.class);
                        } else if (inputtype[i].equals("java.lang.Integer")
                                || inputtype[i].equals("int")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    int.class);
                        } else if (inputtype[i].equals("java.util.List")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    List.class);
                        } else if (inputtype[i].equals("java.lang.Boolean")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    Boolean.class);
                        } else if (inputtype[i].equals("java.math.BigDecimal")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    BigDecimal.class);
                        } else if (inputtype[i].equals("java.lang.String")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    String.class);
                        } else if (inputtype[i].equals("java.lang.Long[]")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    Long[].class);
                        } else if (inputtype[i].equals("java.lang.Integer[]")
                                || inputtype[i].equals("int[]")) {
                            inputvalue[i] = GsonUtil.fromJson(paramsstr[i],
                                    int[].class);
                        } else if (inputtype[i].equals("java.lang.Object")
                                ) {
                            inputvalue[i] = m;
                        }

                    } else {
                        inputvalue[i] = m;
                    }
                } else {
                    logger.info("check it not jsontype");
                    inputvalue[i] = paramsstr[i];
                }
            }
        }
        // else {
        // params=null;
        //}
        logger.info(inputvalue == null ? null : JSONArray.toJSON(inputvalue).toString());
        Object result = new Object();
        String resultValue = "error";
        try {
            result = genericService.$invoke(uniqueServiceDefined.getServiceMethod(), uniqueServiceDefined.getServiceInputDto().split("\\|\\|"), inputvalue);
        } catch (Exception e) {
            logger.error("rpc errorr", e);
            new Exception("rpc exception", e);
        }
        Object targetDataSet = DubboResultHelper.handlerResultSet(result);
        try {
            if (targetDataSet instanceof String) {
                resultValue = (String) targetDataSet;
            } else {
                resultValue = JSONMapper.toJSON(targetDataSet).render(true);
            }
            logger.info("return result:" + resultValue);
        } catch (MapperException e) {
            logger.error("json error", e);
            new Exception("json exception", e);
        }
        return resultValue;
    }


    public void setupTest() {
        //
        logger.info("setupTest");
    }


    /**
     *
     *
     * @return
     */
    public void setValues(JavaSamplerContext arg0) {
        //
        protocol = arg0.getParameter("Protocol");
        address = arg0.getParameter("Address");
        client = arg0.getParameter("Client");
        timeout = arg0.getIntParameter("Timeout");
        serviceInterfaceName = arg0.getParameter("ServiceInterfaceName");
        serviceMethod = arg0.getParameter("ServiceMethod");
        serviceInputDto = arg0.getParameter("ServiceInputDto");
        serviceVersion = arg0.getParameter("ServiceVersion");
        params = arg0.getParameter("Params");
    }


    public SampleResult runTest(JavaSamplerContext arg0) {
        SampleResult sr = new SampleResult();
        setValues(arg0);
        sr.sampleStart();
        sr.setSampleLabel(serviceInterfaceName);
        /*sr.setSamplerData(">>>dubbo invoke"+protocol+"//"+address+"\n"+"serviceInterFace"+serviceInterfaceName+"\n"+
" Method:"+serviceMethod+"\n"+
"serviceType"+serviceInputDto+"\n"+
" Version:"+serviceVersion+"\n"+
"Params:"+params+"\n"+
"} >>>");*/
        logger.info(">>>dubbo invoke" + protocol + "//" + address + "/" + serviceInterfaceName + " Method:" + serviceMethod + " Version:" + serviceVersion + "} >>>");
        start = System.currentTimeMillis();
        try {
            // dubb
            RegistryConfig registry = new RegistryConfig();
            registry.setProtocol(protocol);
            registry.setAddress(address);
            registry.setClient(client);
            registry.setTimeout(timeout);


            UniqueServiceDefined usd = new UniqueServiceDefined();
            usd.setServiceInterfaceName(serviceInterfaceName);
            usd.setServiceMethod(serviceMethod);
            usd.setServiceInputDto(serviceInputDto);
            usd.setServiceVersion(serviceVersion);
            //
            String result = call(registry, usd, params);
            Long tmp = System.currentTimeMillis();
            // jmeter
            sr.setSuccessful(true);
            sr.setResponseData(result, null);
            sr.setDataType(SampleResult.TEXT);
            sr.setDataEncoding("GBK");
            sr.setResponseMessageOK();
            sr.setResponseCode("200");
            //sr.setRequestHeaders(serviceInterfaceName);
            sr.setRequestHeaders(protocol + "://" + address + "\n" + "serviceInterFace:" + serviceInterfaceName + "\n" +
                    "Method:" + serviceMethod + "\n" +
                    "serviceType:" + serviceInputDto + "\n" +
                    "Version:" + serviceVersion + "\n" +
                    "Params:" + params + "\n" + "tranTime:" + (tmp - start));




        } catch (Exception e) {
            logger.error("LqueryTakeRegNo response error : ", e);
            sr.setResponseMessage("LqueryTakeRegNo response error : " + e.getMessage());
            sr.setResponseCode("500");
            sr.setSuccessful(false);
        } finally {
            sr.sampleEnd();// jmeter
            logger.info(">>> dubbo invoke{" + protocol + "//" + address + "/" + serviceInterfaceName + " Method:" + serviceMethod + " Version:" + serviceVersion + "} >>>");
        }
        return sr;
    }


    public Arguments getDefaultParameters() {
        //
        Arguments params = new Arguments();
        params.addArgument("Protocol", "");
        params.addArgument("Address", "");
        params.addArgument("Client", "");
        params.addArgument("Timeout", "");
        params.addArgument("ServiceInterfaceName", "");
        params.addArgument("ServiceMethod", "");
        params.addArgument("ServiceInputDto", "");
        params.addArgument("ServiceVersion", "");
        params.addArgument("Params", "");
        return params;
    }


    public void teardownTest(JavaSamplerContext arg0) {
        cache.destroyAll();
        reference.destroy();
        super.teardownTest(arg0);


        end = System.currentTimeMillis();
        logger.info("tran time: " + (end - start) + "ms");


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值