前面写了一些测试dubbo接口的插件,但在做功能测试的时候有些不是很好用,然后就根据实际测试的操作习惯又慢慢的优化一些,重新编写了一个Jmeter测试dubbo接口的插件,用了蛮长时间了感觉还不错,支持存储接口信息(使用的SQLite,数据库文件可直接放在bin目录下),还对请求参数做了处理,使用更易读的json风格传递参数并支持格式化等(此插件偏向于做接口功能测试,不建议用这个插件做性能测试)。(另外本人非专业的开发人员,只是对编码比较感兴趣的一测试,不喜勿喷,可提优化建议)
此插件写的时候是集成在jmeter源码中的,感兴趣的也可单独启一个项目
直接上源码
dubbo invoke
package org.apache.jmeter.protocol.sgr.dubbo.invoker;
import org.apache.jmeter.protocol.sgr.dubbo.config.ReferenceConfigReq;
public interface DubboInvoker {
void config(ReferenceConfigReq referenceConfigReq);
Object $invoke(String method, String[] parameterTypes, Object[] parameterList,String appids);
}
package org.apache.jmeter.protocol.sgr.dubbo.config;
public class ReferenceConfigReq {
private ApplicationConfigReq application;
private String url;
private RegistryConfigReq registry;
private String protocol;
private Integer timeout;
private Integer retries;
private String version;
private String cluster;
private String group;
private Integer connections;
private String loadBalance;
private boolean generic;
private String serviceInterface;
public ApplicationConfigReq getApplication() {
return application;
}
public void setApplication(ApplicationConfigReq application) {
this.application = application;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public RegistryConfigReq getRegistry() {
return registry;
}
public void setRegistry(RegistryConfigReq registry) {
this.registry = registry;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Integer getConnections() {
return connections;
}
public void setConnections(Integer connections) {
this.connections = connections;
}
public String getLoadBalance() {
return loadBalance;
}
public void setLoadBalance(String loadBalance) {
this.loadBalance = loadBalance;
}
public boolean isGeneric() {
return generic;
}
public void setGeneric(boolean generic) {
this.generic = generic;
}
public String getInterface() {
return serviceInterface;
}
public void setInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.invoker.impl;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.protocol.sgr.dubbo.config.ReferenceConfigReq;
import org.apache.jmeter.protocol.sgr.dubbo.invoker.DubboInvoker;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.util.JsonUtils;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.util.Sha1Utils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.utils.ReferenceConfigCache;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class OldDubboInvoker implements DubboInvoker {
private final com.alibaba.dubbo.config.ReferenceConfig<GenericService> reference = new com.alibaba.dubbo.config.ReferenceConfig<>();
private GenericService genericService;
@Override
public void config(ReferenceConfigReq referenceConfigReq) {
ApplicationConfig application = new ApplicationConfig();
application.setName(referenceConfigReq.getApplication().getName());
reference.setApplication(application);
if (referenceConfigReq.getUrl() != null) {
reference.setUrl(referenceConfigReq.getUrl());
} else {
RegistryConfig registry = new RegistryConfig();
registry.setProtocol(referenceConfigReq.getRegistry().getProtocol());
registry.setGroup(referenceConfigReq.getRegistry().getGroup());
registry.setAddress(referenceConfigReq.getRegistry().getAddress());
reference.setRegistry(registry);
}
reference.setProtocol(referenceConfigReq.getProtocol());
reference.setTimeout(referenceConfigReq.getTimeout());
reference.setRetries(referenceConfigReq.getRetries());
reference.setVersion(referenceConfigReq.getVersion());
reference.setCluster(referenceConfigReq.getCluster());
reference.setGroup(referenceConfigReq.getGroup());
reference.setConnections(referenceConfigReq.getConnections());
reference.setLoadbalance(referenceConfigReq.getLoadBalance());
reference.setGeneric(referenceConfigReq.isGeneric());
reference.setInterface(referenceConfigReq.getInterface());
ReferenceConfigCache cache = ReferenceConfigCache.getCache(referenceConfigReq.getRegistry().getAddress(), com.alibaba.dubbo.config.ReferenceConfig::toString);
genericService = cache.get(reference);
}
@Override
public Object $invoke(String method, String[] parameterTypes, Object[] parameterList,String appids) {
//调用接口前,处理dubbo上下文信息
if (StringUtils.isNotBlank(appids)) {
if (JsonUtils.isJson(appids)) {
org.json.JSONObject jsonobj = new org.json.JSONObject(appids);
Iterator<String> male_Iterator = jsonobj.keys();
while (male_Iterator.hasNext()) {
String key = male_Iterator.next();
RpcContext.getContext().setAttachment(key, jsonobj.getString(key));
}
}
}
return genericService.$invoke(method, parameterTypes, parameterList);
}
}
Jmeter Gui 配置
package org.apache.jmeter.protocol.sgr.config.gui;
import java.awt.*;
import javax.swing.*;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.config.gui.AbstractConfigGui;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.gui.DubboCommonPanel;
import org.apache.jmeter.testelement.TestElement;
public class DubboDefaultsGui extends AbstractConfigGui {
private DubboCommonPanel commonPanel = new DubboCommonPanel();
public DubboDefaultsGui() {
super();
init();
}
@Override
public String getLabelResource() {
return this.getClass().getSimpleName();
}
@Override
public String getStaticLabel() {
return "Myb Dubbo Defaults";
}
@Override
public TestElement createTestElement() {
ConfigTestElement config = new ConfigTestElement();
modifyTestElement(config);
return config;
}
@Override
public void modifyTestElement(TestElement testElement) {
testElement.clear();
super.configureTestElement(testElement);
commonPanel.modifyTestElement(testElement);
}
@Override
public void configure(TestElement testElement) {
super.configure(testElement);
commonPanel.configure(testElement);
}
@Override
public void clearGui() {
super.clearGui();
commonPanel.resetFieldsToDefault();
}
private void init() {
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
add(makeConfigPanel(), BorderLayout.CENTER);
commonPanel.resetFieldsToDefault();
}
private JPanel makeConfigPanel() {
JPanel container = new VerticalPanel(5, 0);
container.add(commonPanel.makeRegistryPanel());
container.add(commonPanel.makeServicePanel());
return container;
}
}
package org.apache.jmeter.protocol.sgr.control.gui;
import java.awt.*;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.gui.DubboPanel;
import org.apache.jmeter.protocol.sgr.sampler.DubboSampler;
import org.apache.jmeter.samplers.gui.AbstractSamplerGui;
import org.apache.jmeter.testelement.TestElement;
public class DubboSamplerGui extends AbstractSamplerGui {
private final DubboPanel panel;
public DubboSamplerGui() {
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
add(makeTitlePanel(), BorderLayout.NORTH);
panel = new DubboPanel();
add(panel.init(), BorderLayout.CENTER);
}
@Override
public String getStaticLabel() {
return "Myb Dubbo Sampler";
}
@Override
public String getLabelResource() {
return this.getClass().getSimpleName();
}
@Override
public TestElement createTestElement() {
DubboSampler sampler = new DubboSampler();
modifyTestElement(sampler);
return sampler;
}
@Override
public void configure(TestElement element) {
super.configure(element);
panel.configure(element);
}
@Override
public void modifyTestElement(TestElement testElement) {
super.configureTestElement(testElement);
panel.modifyTestElement(testElement);
}
@Override
public void clearGui() {
super.clearGui();
panel.clearFields();
}
}
布局 以及一些处理
package org.apache.jmeter.protocol.sgr.dubbo.jmeter.gui;
import java.awt.*;
import java.util.Objects;
import javax.swing.*;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.gui.JLabeledTextField;
public class DubboCommonPanel {
private JComboBox<String> registryProtocol;
private JLabeledTextField registryAddress;
private JLabeledTextField registryGroup;
private JComboBox<String> rpcProtocol;
private JLabeledTextField serviceTimeout;
private JLabeledTextField serviceRetries;
private JComboBox<String> serviceCluster;
private JLabeledTextField serviceConnections;
private JComboBox<String> serviceLoadBalance;
// private JLabeledTextField serviceGroup;
// private JLabeledTextField serviceVersion;
// private JLabeledTextField serviceAppid;
void clearFields() {
registryProtocol.setSelectedItem("");
registryAddress.setText("");
registryGroup.setText("");
rpcProtocol.setSelectedItem("");
serviceTimeout.setText("");
serviceRetries.setText("");
// serviceVersion.setText("");
serviceCluster.setSelectedItem("");
// serviceGroup.setText("");
serviceConnections.setText("");
serviceLoadBalance.setSelectedItem("");
// serviceAppid.setText("");
}
public void resetFieldsToDefault() {
clearFields();
registryProtocol.removeItem("");
rpcProtocol.removeItem("");
serviceCluster.removeItem("");
serviceLoadBalance.removeItem("");
registryProtocol.setSelectedItem("zookeeper");
rpcProtocol.setSelectedItem("dubbo");
serviceTimeout.setText("120000");
serviceRetries.setText("0");
serviceCluster.setSelectedItem("failfast");
serviceConnections.setText("100");
serviceLoadBalance.setSelectedItem("random");
}
public void configure(TestElement testElement) {
registryProtocol.setSelectedItem(testElement.getPropertyAsString(DubboElement.REGISTRY_PROTOCOL));
registryAddress.setText(testElement.getPropertyAsString(DubboElement.REGISTRY_ADDRESS));
registryGroup.setText(testElement.getPropertyAsString(DubboElement.REGISTRY_GROUP));
rpcProtocol.setSelectedItem(testElement.getPropertyAsString(DubboElement.RPC_PROTOCOL));
serviceTimeout.setText(testElement.getPropertyAsString(DubboElement.SERVICE_TIMEOUT));
serviceRetries.setText(testElement.getPropertyAsString(DubboElement.SERVICE_RETRIES));
// serviceVersion.setText(testElement.getPropertyAsString(DubboElement.SERVICE_VERSION));
serviceCluster.setSelectedItem(testElement.getPropertyAsString(DubboElement.SERVICE_CLUSTER));
// serviceGroup.setText(testElement.getPropertyAsString(DubboElement.SERVICE_GROUP));
serviceConnections.setText(testElement.getPropertyAsString(DubboElement.SERVICE_CONNECTIONS));
serviceLoadBalance.setSelectedItem(testElement.getPropertyAsString(DubboElement.SERVICE_LOAD_BALANCE));
// serviceAppid.setText(testElement.getPropertyAsString(DubboElement.SERVICE_APPID));
}
public void modifyTestElement(TestElement testElement) {
testElement.setProperty(DubboElement.REGISTRY_PROTOCOL, Objects.requireNonNull(registryProtocol.getSelectedItem()).toString());
testElement.setProperty(DubboElement.REGISTRY_ADDRESS, registryAddress.getText());
testElement.setProperty(DubboElement.REGISTRY_GROUP, registryGroup.getText());
testElement.setProperty(DubboElement.RPC_PROTOCOL, Objects.requireNonNull(rpcProtocol.getSelectedItem()).toString());
testElement.setProperty(DubboElement.SERVICE_TIMEOUT, serviceTimeout.getText());
testElement.setProperty(DubboElement.SERVICE_RETRIES, serviceRetries.getText());
// testElement.setProperty(DubboElement.SERVICE_VERSION, serviceVersion.getText());
testElement.setProperty(DubboElement.SERVICE_CLUSTER, Objects.requireNonNull(serviceCluster.getSelectedItem()).toString());
// testElement.setProperty(DubboElement.SERVICE_GROUP, serviceGroup.getText());
testElement.setProperty(DubboElement.SERVICE_CONNECTIONS, serviceConnections.getText());
testElement.setProperty(DubboElement.SERVICE_LOAD_BALANCE, Objects.requireNonNull(serviceLoadBalance.getSelectedItem()).toString());
// testElement.setProperty(DubboElement.SERVICE_APPID, serviceAppid.getText());
}
public JPanel makeRegistryPanel() {
JPanel registryPanel = new JPanel();
registryPanel.setLayout(new WrapLayout(FlowLayout.LEADING, 5, 5));
registryPanel.setBorder(BorderFactory.createTitledBorder("Registry"));
registryPanel.add(new JLabel("Protocol: "));
registryPanel.add(registryProtocol = new JComboBox<>(new String[]{"", "zookeeper", "none", "multicast", "redis", "simple"}));
registryPanel.add(registryAddress = new JLabeledTextField("Address: ", 26));
registryPanel.add(registryGroup = new JLabeledTextField("Group: ", 6));
return registryPanel;
}
public JPanel makeServicePanel() {
JPanel servicePanel = new JPanel();
servicePanel.setLayout(new WrapLayout(FlowLayout.LEADING, 5, 5));
servicePanel.setBorder(BorderFactory.createTitledBorder("Service"));
servicePanel.add(new JLabel("Protocol: "));
servicePanel.add(rpcProtocol = new JComboBox<>(new String[]{"", "dubbo", "rmi", "hessian", "http", "webservice", "thrift", "memcached", "redis", "rest"}));
servicePanel.add(serviceTimeout = new JLabeledTextField("Timeout: ", 6));
servicePanel.add(serviceRetries = new JLabeledTextField("Retries: ", 6));
servicePanel.add(new JLabel("Cluster: "));
servicePanel.add(serviceCluster = new JComboBox<>(new String[]{"", "failover", "failsafe", "failfast", "failback", "forking"}));
servicePanel.add(serviceConnections = new JLabeledTextField("Connections: ", 6));
servicePanel.add(new JLabel("Load Balance: "));
servicePanel.add(serviceLoadBalance = new JComboBox<>(new String[]{"", "random", "roundrobin", "leastactive", "consistenthash"}));
// servicePanel.add(serviceGroup = new JLabeledTextField(" Group: ", 6));
// servicePanel.add(serviceVersion = new JLabeledTextField("Version: ", 6));
// servicePanel.add(serviceAppid = new JLabeledTextField("Appid: ", 20));
return servicePanel;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.jmeter.gui;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.apache.jmeter.protocol.sgr.dubbo.config.ApplicationConfigReq;
import org.apache.jmeter.protocol.sgr.dubbo.config.ReferenceConfigReq;
import org.apache.jmeter.protocol.sgr.dubbo.config.RegistryConfigReq;
import org.apache.jmeter.protocol.sgr.dubbo.invoker.DubboInvoker;
import org.apache.jmeter.protocol.sgr.dubbo.invoker.DubboInvokerFactory;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.dto.DubboParamDto;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.util.JsonUtils;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.AbstractTestElement;
public class DubboElement implements Serializable {
private static final String DTO_ARRAY_SUFFIX = "[]";
private static final String DTO_LIST_SUFFIX = "java.util.List";
private static final String DTO_MAP_SUFFIX = "java.util.Map";
private static final String BASIC_TYPE_NUMBER = "java.lang.Short,java.lang.Integer,java.lang.Float,java.lang.Double,java.lang.Byte";
private static final String BASIC_TYPE_STRING =
"java.lang.String" + "java.lang.String[]java.lang.String[][]" + "java.lang.Character"
+ "java.lang.Character[]" + "java.lang.Character[][]java.lang.Number[]"
+ "java.lang.Number[][]java.lang.Number" + "java.lang.Short[]"
+ "java.lang.Short[][]java.lang.Shortjava.lang.Integer[]" + "java.lang.Integer[][]java.lang.Integer"
+ "java.lang.Long[]"
+ "java.lang.Long[][]java.lang.Long" + "java.lang.Float[]"
+ "java.lang.Float[][]java.lang.Floatjava.lang.Double[]" + "java.lang.Double[][]java.lang.Double"
+ "java.lang.Boolean[]"
+ "java.lang.Boolean[][]java.lang.Boolean" + "java.lang.Byte[]" + "java.lang.Byte[][]java.lang.Byte"
+ "char" + "char[]" + "char[][]int" + "int[]int[][]short" + "short[]"
+ "short[][]long" + "long[]long[][]boolean" + "boolean[]" + "boolean[][]float"
+ "float[]float[][]double" + "double[]double[][]byte" + "byte[]byte[][]" + "java.util.Date"
+ "java.util.Map" + "java.util.List"
+ "java.io.InputStream" + "java.util.Set" + "java.lang.Object" + "java.math.BigDecimal"
+ "java.math.BigIntegerObject" + "java.util.UUID";
static final String REGISTRY_PROTOCOL = "registryProtocol";
static final String REGISTRY_ADDRESS = "registryAddress";
static final String REGISTRY_GROUP = "registryGroup";
static final String RPC_PROTOCOL = "rpcProtocol";
static final String SERVICE_TIMEOUT = "serviceTimeout";
static final String SERVICE_RETRIES = "serviceRetries";
static final String SERVICE_VERSION = "serviceVersion";
static final String SERVICE_CLUSTER = "serviceCluster";
static final String SERVICE_GROUP = "serviceGroup";
static final String SERVICE_CONNECTIONS = "serviceConnections";
static final String SERVICE_LOAD_BALANCE = "serviceLoadBalance";
static final String SYSTEM_NAME = "systemName";
static final String SERVICE_INTERFACE = "serviceInterface";
static final String SERVICE_METHOD = "serviceMethod";
static final String SERVICE_PARAMETER = "serviceParameter";
static final String SERVICE_APPID = "serviceAppid";
private AbstractTestElement model;
public DubboElement(AbstractTestElement model) {
this.model = model;
}
public SampleResult sample() {
SampleResult sampleResult = new SampleResult();
sampleResult.sampleStart();
sampleResult.setSampleLabel(model.getName());
dubboInvoke(sampleResult);
sampleResult.setDataType(SampleResult.TEXT);
sampleResult.setResponseCodeOK();
sampleResult.setResponseMessageOK();
sampleResult.sampleEnd();
return sampleResult;
}
private void dubboInvoke(SampleResult sampleResult) {
DubboParamDto parameters;
try {
if (StringUtils.isNotBlank(getServiceParameter())) {
parameters = parseParameter(getServiceParameter());
} else {
parameters = new DubboParamDto();
}
// parameters = YamlParamParser.parseParameter(getServiceParameter());
} catch (Exception e) {
sampleResult.setSuccessful(false);
sampleResult.setResponseData(JsonUtils.toJson(e), StandardCharsets.UTF_8.name());
return;
}
String[] parameterTypes = parameters.getTypes();
//参数处理
Object[] parameterValues = parameters.getValues();
String samplerData = getSampleData();
sampleResult.setSamplerData(samplerData);
ApplicationConfigReq application = new ApplicationConfigReq();
application.setName("Myb-Dubbo-Sample");
ReferenceConfigReq reference = new ReferenceConfigReq();
reference.setApplication(application);
RegistryConfigReq registry = new RegistryConfigReq();
registry.setProtocol(getRegistryProtocol());
registry.setGroup(getRegistryGroup());
registry.setAddress(getRegistryAddress());
reference.setRegistry(registry);
if ("none".equalsIgnoreCase(getRegistryProtocol())) {
reference.setUrl(getRpcProtocol() + "://" + getRegistryAddress() + "/" + getServiceInterface());
}
reference.setProtocol(getRpcProtocol());
reference.setTimeout(getServiceTimeout());
reference.setRetries(getServiceRetries());
reference.setVersion(getServiceVersion());
reference.setCluster(getServiceCluster());
reference.setGroup(getServiceGroup());
reference.setConnections(getServiceConnections());
reference.setLoadBalance(getServiceLoadBalance());
reference.setGeneric(true);
reference.setInterface(getServiceInterface());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DubboInvoker dubboInvoker = DubboInvokerFactory.get();
try {
dubboInvoker.config(reference);
} catch (Exception e) {
sampleResult.setSuccessful(false);
e.printStackTrace(new PrintWriter(buf, true));
sampleResult.setResponseData("连接注册中心错误: " + buf.toString(), StandardCharsets.UTF_8.name());
return;
}
Object result;
try {
result = dubboInvoker.$invoke(getServiceMethod(), parameterTypes, parameterValues, getServiceAppid());
sampleResult.setSuccessful(true);
try {
sampleResult.setResponseData(JsonUtils.toJson(result), StandardCharsets.UTF_8.name());
} catch (Exception e) {
sampleResult.setResponseData(result.toString(), StandardCharsets.UTF_8.name());
}
} catch (Exception e) {
e.printStackTrace(new PrintWriter(buf, true));
sampleResult.setSuccessful(false);
sampleResult.setResponseData("调用服务错误: " + buf.toString(), StandardCharsets.UTF_8.name());
}
}
private String getSampleData() {
return "Registry Protocol: " + getRegistryProtocol() + "\n" +
"Registry Address: " + getRegistryAddress() + "\n" +
"Registry Group: " + getRegistryGroup() + "\n" +
"RPC Protocol: " + getRpcProtocol() + "\n" +
"Service Timeout: " + getServiceTimeout() + "\n" +
"Service Retries: " + getServiceRetries() + "\n" +
"Service Version: " + getServiceVersion() + "\n" +
"Service Cluster: " + getServiceCluster() + "\n" +
"Service Group: " + getServiceGroup() + "\n" +
"Service Connections: " + getServiceConnections() + "\n" +
"Service Load Balance: " + getServiceLoadBalance() + "\n" +
"Service Appid: " + getServiceAppid() + "\n" +
"Interface: " + getServiceInterface() + "\n" +
"Method: " + getServiceMethod() + "\n" +
"Parameter: \n" + getServiceParameter() + "\n";
}
private String getRegistryProtocol() {
return getPropertyAsString(REGISTRY_PROTOCOL);
}
private String getRegistryAddress() {
return getPropertyAsString(REGISTRY_ADDRESS, "zookeeper");
}
private String getRegistryGroup() {
return getPropertyAsString(REGISTRY_GROUP, "");
}
private String getRpcProtocol() {
return getPropertyAsString(RPC_PROTOCOL, "dubbo");
}
private int getServiceTimeout() {
return getPropertyAsInteger(SERVICE_TIMEOUT, 120000);
}
private int getServiceRetries() {
return getPropertyAsInteger(SERVICE_RETRIES, 0);
}
private String getServiceVersion() {
return getPropertyAsString(SERVICE_VERSION, "");
}
private String getServiceCluster() {
return getPropertyAsString(SERVICE_CLUSTER, "failfast");
}
private String getServiceGroup() {
return getPropertyAsString(SERVICE_GROUP, "");
}
private Integer getServiceConnections() {
return getPropertyAsInteger(SERVICE_CONNECTIONS, 100);
}
private String getServiceLoadBalance() {
return getPropertyAsString(SERVICE_LOAD_BALANCE, "random");
}
private String getServiceAppid() {
return getPropertyAsString(SERVICE_APPID, "");
}
private String getSystemName() {
return getPropertyAsString(SYSTEM_NAME, "Interface");
}
private String getServiceInterface() {
return getPropertyAsString(SERVICE_INTERFACE);
}
private String getServiceMethod() {
return getPropertyAsString(SERVICE_METHOD);
}
private String getServiceParameter() {
return getPropertyAsString(SERVICE_PARAMETER);
}
private String getPropertyAsString(String key) {
return model.getPropertyAsString(key);
}
private String getPropertyAsString(String key, String defaultValue) {
return model.getPropertyAsString(key, defaultValue);
}
private Integer getPropertyAsInteger(String key, Integer defaultValue) {
Integer value = defaultValue;
try {
value = Integer.valueOf(model.getPropertyAsString(key));
} catch (NumberFormatException ignored) {
}
return value;
}
/**
* 参数转化为符合泛化调用类型的参数
*
* @param param 参数
* @return DubboParamPO
*/
public static DubboParamDto parseParameter(String param) {
LinkedHashMap<String, Object> params = JSON.parseObject(param, LinkedHashMap.class, Feature.OrderedField);
DubboParamDto dubboParam = new DubboParamDto(params.size());
String[] types = dubboParam.getTypes();
Object[] values = dubboParam.getValues();
Iterator<String> iter = params.keySet().iterator();
int i = 0;
while (iter.hasNext()) {
String key = iter.next();
String value = params.get(key) + "";
key = key.replaceAll("\\d+", "");
if (key.endsWith(DTO_ARRAY_SUFFIX) || key.startsWith(DTO_LIST_SUFFIX)) {
types[i] = key;
if (!"null".equals(value.toLowerCase())) {
values[i] = JSONArray.parseArray(value);
}
} else if (!BASIC_TYPE_STRING.contains(key) || key.startsWith(DTO_MAP_SUFFIX)) {
types[i] = key;
if (!"null".equals(value.toLowerCase())) {
values[i] = JSONObject.parseObject(value);
}
} else if ("java.util.UUID".equals(key)) {
types[i] = key;
if (!"null".equals(value.toLowerCase())) {
values[i] = UUID.randomUUID();
}
} else if (key.contains("LocalDateTime")) {
types[i] = key;
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime valueTemp = LocalDateTime.parse(value, df);
values[i] = valueTemp;
// System.out.println(Arrays.toString(values));
} else {
types[i] = key;
Object valueTemp = value;
if (!"null".equals(value.toLowerCase())) {
if (BASIC_TYPE_NUMBER.contains(key)) {
if (key.contains(".")) {
valueTemp = Double.parseDouble(value);
} else {
valueTemp = Long.parseLong(value);
}
}
values[i] = valueTemp;
}
}
if (JsonUtils.isJson(value)) {
JSONObject jsonObject = JSONObject.parseObject(value);
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
Object elValue = entry.getValue();
if (String.valueOf(elValue).contains("LDT")) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime valueTemp = LocalDateTime
.parse(String.valueOf(elValue).substring(0, String.valueOf(elValue).indexOf("LDT")),
df);
jsonObject.put(entry.getKey(), valueTemp);
}
}
values[i] = jsonObject;
System.out.println(jsonObject);
}
i++;
}
return dubboParam;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.jmeter.gui;
import java.awt.*;
import java.util.List;
import java.util.Objects;
import javax.swing.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.gui.util.VerticalPanel;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.util.JDBCUtil;
import org.apache.jmeter.protocol.sgr.dubbo.jmeter.util.JsonUtils;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.gui.JLabeledTextField;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class DubboPanel {
private DubboCommonPanel commonPanel = new DubboCommonPanel();
private JComboBox<String> systemName;
private JComboBox<String> serviceInterface;
private JComboBox<String> serviceMethod;
private JTextArea serviceParameter;
private JLabeledTextField serviceGroup;
private JLabeledTextField serviceVersion;
private JLabeledTextField serviceAppid;
public JPanel init() {
JPanel container = new VerticalPanel(5, 0);
container.add(commonPanel.makeRegistryPanel());
container.add(commonPanel.makeServicePanel());
container.add(makeTempPanel());
container.add(makeParameterPanel());
clearFields();
return container;
}
public void clearFields() {
commonPanel.clearFields();
serviceVersion.setText("");
serviceGroup.setText("");
serviceAppid.setText("");
systemName.setSelectedItem("Interface");
serviceInterface.setSelectedItem("");
serviceMethod.setSelectedItem("");
serviceParameter.setText("");
}
public void configure(TestElement testElement) {
commonPanel.configure(testElement);
serviceGroup.setText(testElement.getPropertyAsString(DubboElement.SERVICE_GROUP));
serviceVersion.setText(testElement.getPropertyAsString(DubboElement.SERVICE_VERSION));
serviceAppid.setText(testElement.getPropertyAsString(DubboElement.SERVICE_APPID));
systemName.setSelectedItem(testElement.getPropertyAsString(DubboElement.SYSTEM_NAME));
serviceInterface.setSelectedItem(testElement.getPropertyAsString(DubboElement.SERVICE_INTERFACE));
serviceMethod.setSelectedItem(testElement.getPropertyAsString(DubboElement.SERVICE_METHOD));
serviceParameter.setText(testElement.getPropertyAsString(DubboElement.SERVICE_PARAMETER));
}
public void modifyTestElement(TestElement testElement) {
commonPanel.modifyTestElement(testElement);
testElement.setProperty(DubboElement.SERVICE_GROUP, serviceGroup.getText());
testElement.setProperty(DubboElement.SERVICE_VERSION, serviceVersion.getText());
testElement.setProperty(DubboElement.SERVICE_APPID, serviceAppid.getText());
testElement.setProperty(DubboElement.SYSTEM_NAME, Objects.requireNonNull(systemName.getSelectedItem()).toString());
testElement.setProperty(DubboElement.SERVICE_INTERFACE, Objects.requireNonNull(serviceInterface.getSelectedItem()).toString());
testElement.setProperty(DubboElement.SERVICE_METHOD, Objects.requireNonNull(serviceMethod.getSelectedItem()).toString());
testElement.setProperty(DubboElement.SERVICE_PARAMETER, serviceParameter.getText());
}
private JPanel makeTempPanel() {
JPanel gridPanel1 = new JPanel(new GridBagLayout());
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
GridBagConstraints editConstraints = new GridBagConstraints();
editConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
editConstraints.weightx = 1.0;
editConstraints.fill = GridBagConstraints.HORIZONTAL;
GridBagConstraints buttonConstraints = new GridBagConstraints();
buttonConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
buttonConstraints.weightx = 1.0;
buttonConstraints.gridx = 0;
// serviceGroup = new JLabeledTextField(" Group: ", 6);
// serviceVersion = new JLabeledTextField("Version: ", 6);
// serviceAppid = new JLabeledTextField("Appid: ", 20);
addToPanel(gridPanel1, labelConstraints, 0, 0, serviceGroup = new JLabeledTextField(" Group: ", 10));
// serviceGroup = new JLabeledTextField();
// addToPanel(gridPanel1, editConstraints, 1, 0, serviceGroup);
addToPanel(gridPanel1, labelConstraints, 1, 0, serviceVersion = new JLabeledTextField(" Version: ", 6));
// serviceVersion = new JLabeledTextField();
// addToPanel(gridPanel1, editConstraints, 3, 0, serviceVersion);
addToPanel(gridPanel1, labelConstraints, 2, 0, serviceAppid = new JLabeledTextField(" Appid: ", 20));
// serviceAppid = new JLabeledTextField();
// addToPanel(gridPanel1, editConstraints, 5, 0, serviceAppid);
JButton button2 = new JButton(" save");
button2.addActionListener(e -> {
String sysName = Objects.requireNonNull(systemName.getSelectedItem()).toString();
String service = Objects.requireNonNull(serviceInterface.getSelectedItem()).toString();
String method = Objects.requireNonNull(serviceMethod.getSelectedItem()).toString();
String group = serviceGroup.getText();
String version = serviceVersion.getText();
String appid = serviceAppid.getText();
String parameter = serviceParameter.getText();
String selectSql = "select * from myb_dubbo_services where dubbo_service='" + service + "' and service_method='" + method + "';";
List<Integer> selectRs = JDBCUtil.select(selectSql, 1);
if (selectRs.size() > 0 && !sysName.equals("case")) {
int id = selectRs.get(0);
String updateSql = "update myb_dubbo_services set system_name='" + sysName + "',appid='" + appid + "',dubbo_service='" + service + "',service_method='" + method + "',service_group='" + group + "',service_version='" + version + "',method_param='" + parameter + "' where id='" + id + "';";
JDBCUtil.update(updateSql);
} else {
if(sysName.equals("")){
sysName="others";
}
String insertSql = "insert into myb_dubbo_services(system_name,appid,dubbo_service,service_method,service_group,service_version,method_param) values ('" + sysName + "','" + appid + "','" + service + "','" + method + "','" + group + "','" + version + "','" + parameter + "')";
JDBCUtil.insert(insertSql);
}
});
addToPanel(gridPanel1, buttonConstraints, 3, 0, button2);
// tempPanel.add(serviceGroup = new JLabeledTextField(" Group: ", 6));
// tempPanel.add(serviceVersion = new JLabeledTextField("Version: ", 6));
// tempPanel.add(serviceAppid = new JLabeledTextField("Appid: ", 20));
return gridPanel1;
}
private JPanel makeParameterPanel() {
JPanel gridPanel = new JPanel(new GridBagLayout());
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.anchor = GridBagConstraints.FIRST_LINE_END;
GridBagConstraints editConstraints = new GridBagConstraints();
editConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
editConstraints.weightx = 1.0;
editConstraints.fill = GridBagConstraints.HORIZONTAL;
systemName = new JComboBox<>(new String[]{"Interface"});
systemName.setEditable(true);
List sysNames = JDBCUtil.list("SELECT DISTINCT system_name from myb_dubbo_services;");
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(sysNames));
for (int i = 0; i < jsonArray.size(); i++) {
systemName.addItem(jsonArray.getJSONObject(i).getString("system_name"));
}
systemName.setSize(100, 28);
addToPanel(gridPanel, labelConstraints, 0, 0, systemName);
// addToPanel(gridPanel, labelConstraints, 2, 0, new JLabel("Interface: "));
serviceInterface = new JComboBox<>();
serviceInterface.setEditable(true);
systemName.addActionListener(e -> {
serviceInterface.removeAllItems();
List services = JDBCUtil.list("select DISTINCT dubbo_service from myb_dubbo_services where system_name ='" + systemName.getSelectedItem() + "';");
JSONArray jsonServices = JSONArray.parseArray(JSON.toJSONString(services));
for (int i = 0; i < jsonServices.size(); i++) {
serviceInterface.addItem(jsonServices.getJSONObject(i).getString("dubbo_service"));
}
});
addToPanel(gridPanel, editConstraints, 1, 0, serviceInterface);
addToPanel(gridPanel, labelConstraints, 0, 1, new JLabel("Method: "));
serviceMethod = new JComboBox<>();
serviceMethod.setEditable(true);
serviceInterface.addActionListener(e -> {
serviceMethod.removeAllItems();
String service = serviceInterface.getSelectedItem() + "";
if (service.length() > 1) {
try {
List methods = JDBCUtil.list("select service_method from myb_dubbo_services where dubbo_service ='" + service + "';");
JSONArray jsonMethods = JSONArray.parseArray(JSON.toJSONString(methods));
for (int i = 0; i < jsonMethods.size(); i++) {
JSONObject jsonObject = jsonMethods.getJSONObject(i);
String meth = jsonObject.getString("service_method");
serviceMethod.addItem(meth);
}
} catch (Exception ex) {
serviceMethod.addItem("请检查服务名");
}
}
});
addToPanel(gridPanel, editConstraints, 1, 1, serviceMethod);
serviceMethod.addActionListener(e -> {
serviceParameter.setText("");
String service = serviceInterface.getSelectedItem() + "";
String meth = serviceMethod.getSelectedItem() + "";
List smAll = JDBCUtil.list("select * from myb_dubbo_services where dubbo_service ='" + service + "' and service_method = '" + meth + "';");
JSONArray jsonAll = JSONArray.parseArray(JSON.toJSONString(smAll));
if (jsonAll.size() > 0) {
JSONObject jo = jsonAll.getJSONObject(0);
// String methods = jo.getString("service_method");
// String type = methods.substring(methods.indexOf("(") + 1, methods.lastIndexOf(")"));
String value = jo.getString("method_param");
serviceParameter.setText(value);
}
});
addToPanel(gridPanel, labelConstraints, 0, 2, new JLabel("Parameter: "));
editConstraints.fill = GridBagConstraints.BOTH;
serviceParameter = new JTextArea();
addToPanel(gridPanel, editConstraints, 1, 2, createTextAreaScrollPaneContainer(serviceParameter));
GridBagConstraints buttonConstraints = new GridBagConstraints();
buttonConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
buttonConstraints.weightx = 1.0;
GridBagConstraints buttonConstraints1 = new GridBagConstraints();
buttonConstraints1.gridx=0;
JButton button1 = new JButton("json format");
button1.addActionListener(e -> {
String parameter = serviceParameter.getText();
if (StringUtils.isBlank(parameter)) {
JOptionPane.showMessageDialog(gridPanel.getParent(), "parameter is empty", "error", JOptionPane.ERROR_MESSAGE);
return;
}
if (!JsonUtils.isJson(parameter)) {
JOptionPane.showMessageDialog(gridPanel.getParent(), "invalid json", "error", JOptionPane.ERROR_MESSAGE);
return;
}
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(parameter).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
serviceParameter.setText(gson.toJson(jsonObject));
});
addToPanel(gridPanel, buttonConstraints1, 1, 3, button1);
addToPanel(gridPanel, labelConstraints, 1, 4, new JLabel("Powered by M"));
return gridPanel;
}
private void addToPanel(JPanel panel, GridBagConstraints constraints, int col, int row, JComponent component) {
constraints.gridx = col;
constraints.gridy = row;
panel.add(component, constraints);
}
private JScrollPane createTextAreaScrollPaneContainer(JTextArea textArea) {
JScrollPane ret = new JScrollPane();
textArea.setRows(18);
textArea.setColumns(20);
ret.setViewportView(textArea);
return ret;
}
}
效果图:
其它的一些类
package org.apache.jmeter.protocol.sgr.dubbo.config;
public class ApplicationConfigReq {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.config;
public class ReferenceConfigReq {
private ApplicationConfigReq application;
private String url;
private RegistryConfigReq registry;
private String protocol;
private Integer timeout;
private Integer retries;
private String version;
private String cluster;
private String group;
private Integer connections;
private String loadBalance;
private boolean generic;
private String serviceInterface;
public ApplicationConfigReq getApplication() {
return application;
}
public void setApplication(ApplicationConfigReq application) {
this.application = application;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public RegistryConfigReq getRegistry() {
return registry;
}
public void setRegistry(RegistryConfigReq registry) {
this.registry = registry;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public Integer getTimeout() {
return timeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public Integer getConnections() {
return connections;
}
public void setConnections(Integer connections) {
this.connections = connections;
}
public String getLoadBalance() {
return loadBalance;
}
public void setLoadBalance(String loadBalance) {
this.loadBalance = loadBalance;
}
public boolean isGeneric() {
return generic;
}
public void setGeneric(boolean generic) {
this.generic = generic;
}
public String getInterface() {
return serviceInterface;
}
public void setInterface(String serviceInterface) {
this.serviceInterface = serviceInterface;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.config;
public class RegistryConfigReq {
private String protocol;
private String group;
private String address;
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package org.apache.jmeter.protocol.sgr.dubbo.jmeter.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JDBCUtil {
private static final String Class_Name = "org.sqlite.JDBC";
private static final String DB_URL = "jdbc:sqlite:dubbo_services.db";
// 创建Sqlite数据库连接
private static Connection createConnection() throws SQLException, ClassNotFoundException {
Class.forName(Class_Name);
return DriverManager.getConnection(DB_URL);
}
/**
* 查询一条记录
*
* @param sql sql语句
* @return 查询结果
*/
public Map unique(String sql) {
Map<String, Object> result = null;
Connection connection = null;
try {
connection = createConnection();
PreparedStatement pstat = connection.prepareStatement(sql);
pstat.setQueryTimeout(30);
ResultSet rst = pstat.executeQuery();
//获取到
ResultSetMetaData metaData = rst.getMetaData();
int cols = metaData.getColumnCount();
if (rst.next()) {
//封装一行数据
result = new HashMap<>();
for (int i = 0; i < cols; i++) {
String key = metaData.getColumnName(i + 1);
Object value = rst.getObject(i + 1);
result.put(key, value);
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
// connection close failed.
System.err.println(e);
}
}
return result;
}
/**
* 查询一个列表中的数据
*
* @param sql sql语句
* @return 查询结果
*/
public static List list(String sql) {
List<Object> results = new ArrayList<>();
Connection connection = null;
try {
connection = createConnection();
PreparedStatement pstat = connection.prepareStatement(sql);
pstat.setQueryTimeout(30);
ResultSet rst = pstat.executeQuery();
//获取到
ResultSetMetaData metaData = rst.getMetaData();
int cols = metaData.getColumnCount();
while (rst.next()) {
//封装一行数据
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < cols; i++) {
String key = metaData.getColumnName(i + 1);
Object value = rst.getObject(i + 1);
map.put(key, value);
}
results.add(map);
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
// connection close failed.
System.out.println(e);
}
}
return results;
}
//创建表
public static void createTable(String sql) {
Connection c = null;
Statement stmt = null;
try {
c = createConnection();
stmt = c.createStatement();
// String sql = "CREATE TABLE COMPANY " +
// "(ID INT PRIMARY KEY NOT NULL," +
// " NAME TEXT NOT NULL, " +
// " AGE INT NOT NULL, " +
// " ADDRESS CHAR(50), " +
// " SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Table created successfully");
}
public static void insert(String sql) {
Connection c = null;
Statement stmt = null;
try {
c = createConnection();
c.setAutoCommit(false);
stmt = c.createStatement();
// String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
// "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
stmt.executeUpdate(sql);
// sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " +
// "VALUES (2, 'Allen', 25, 'Texas', 15000.00 );";
// stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
// System.exit(0);
}
System.out.println("Records created successfully");
}
public static List<Integer> select(String sql, int num) {
Connection c = null;
Statement stmt = null;
List<Integer> list = new ArrayList<>();
try {
c = createConnection();
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
if (num == 1) {
int id = rs.getInt("id");
list.add(id);
}
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
// System.exit(0);
}
return list;
}
public static void update(String sql) {
Connection c = null;
Statement stmt = null;
try {
c = createConnection();
c.setAutoCommit(false);
stmt = c.createStatement();
// String sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1;";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
// System.exit(0);
}
System.out.println("Operation done successfully");
}
public void delete() {
Connection c = null;
Statement stmt = null;
try {
c = createConnection();
c.setAutoCommit(false);
stmt = c.createStatement();
String sql = "DELETE from COMPANY where ID=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery("SELECT * FROM COMPANY;");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println("ID = " + id);
System.out.println("NAME = " + name);
System.out.println("AGE = " + age);
System.out.println("ADDRESS = " + address);
System.out.println("SALARY = " + salary);
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
// System.exit(0);
}
System.out.println("Operation done successfully");
}
}