说明:最后一个文件到这里下载
所有代码如下
package cn.com.functions;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.threads.JMeterVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RandomPhone extends AbstractFunction {
private static final List<String> desc = new LinkedList();
private static final String KEY = "__RandomPhoneNumber";
private Object[] values;
private static final Logger log = LoggerFactory.getLogger("testing");//这里是实例化log对象并调用debug方法进行调试
static {
desc.add("Name of variable in which to store the result (optional)");
}
private static final String[] telFirst = "134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153"
.split(",");
String phonenumberString = "";
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
JMeterVariables vars = getVariables();
try {
Random random = new Random();
String pheonindexString = telFirst[random.nextInt(telFirst.length)];
String two = String.valueOf(random.nextInt(999) + 1000);
String three = String.valueOf(random.nextInt(999) + 1000);
phonenumberString = pheonindexString + two + three;
if (vars != null && this.values.length > 0) {
String varName = ((CompoundVariable) this.values[0]).execute().trim();
vars.put(varName, this.phonenumberString);
}
if (log.isDebugEnabled()) {//如果开启debug模式,这会在jmeter控制台打印如下语句。用于调试使用
log.debug(" 手机号段:{} 手机号是:{}", pheonindexString, phonenumberString);
}
} catch (Exception e) {
e.printStackTrace();
}
return phonenumberString;
}
public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
checkMinParameterCount(parameters, 0);
this.values = parameters.toArray();
}
public String getReferenceKey() {
return KEY;
}
public List<String> getArgumentDesc() {
return desc;
}
}
然后导入jmeter中查看导入结果:
可以看出函数运行正常。
参考:https://github.com/ufctester/apache-jmeter/tree/master/src/functions/org/apache/jmeter/functions
联系客服