压力测试是对系统不断施加压力的测试,是通过确定一个系统的瓶颈或者不能接收的性能点,来获得系统能提供的最大服务级别的测试。例如测试一个 Web 站点在大量的负荷下,何时系统的响应会退化或失败。网络游戏中也常用到这个词汇。
我们在日常一个系统的交付过程中,需要对系统进行压力测试,即单位时间内相应数的测试,常用在web以及数据库和其他网络服务器的开发交付中,对于web的压力测试我们可以选择ab之类的,而jmeter原先是为了web压力测试产生的,目前更是通过插件扩充到了可以进行包括数据库在内的各种压力测试。
作为一名开发人员,有时候一些简单的测试就不必要动用到那些工具了,就自己写一些代码去搞定了。在写代码的过程中,发觉大部分的压力测试都是统一的模式去做,需要改变的只是不同业务代码。所以我将其抽离成为一个模版类。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
/**
* Commons Test
* lsz
*/
public abstract class AbstractTest
{
int threadNum = 1;
int sleepTime = 1000;
long lastTimes = 0;
int x = 0;
private AtomicLong now = new AtomicLong();
private AtomicLong maxTime = new AtomicLong(0l);
ExecutorService pool = null;
AbstractTest(){
this(5);
}
public AbstractTest(int threadNum) {
this.threadNum = threadNum;
pool = Executors.newScheduledThreadPool(this.threadNum);
}
public abstract void testThreadMethod() throws InterruptedException;
public void start(){
for(int i = 0 ; i<threadNum;i ++ ){
pool.execute(new TestThread());
}
String format = "---------------------"+"当前1s内的执行数"+"/"+"总的执行数"+"/"+"平均的执行数"+"/"+"执行的时间"+"/"+"最长执行时间";
while(true){
try {
x++;
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
long nowtmp = now.get();
System.out.println(format);
System.out.println("---------------------"+(nowtmp - lastTimes)+"/"+now.intValue()+"/"+(now.intValue()/x)+"/"+x+"/"+maxTime.get()+"ms");
lastTimes = nowtmp;
}
}
class TestThread extends Thread{
public TestThread() {
}
@Override
public void run() {
System.out.println("start------------------"+Thread.currentThread().getName());
while (true){
try {
long start = System.currentTimeMillis();
testThreadMethod();
long end = System.currentTimeMillis() - start;
if(end>maxTime.get()){
maxTime.set(end);
}
now.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
"---------------------"+"当前1s内的执行数"+"/"+"总的执行数"+"/"+"平均的执行数"+"/"+"执行的时间"+"/"+"最长执行时间"
这句话是我输出的内容,这几个结果刚好能够简单的衡量一个系统的性能了。接下来可以看到如何使用这个模版类,也是很简单。只需要实现一个模版方法和指定线程数的重载构造方法即可。
/**
* Created by lsz on 14-10-22.
*/
public class SimpleTest extends AbstractTest {
public SimpleTest(int threadNum) {
super(threadNum);
}
@Override
public void testThreadMethod() throws InterruptedException {
//具体要测试的逻辑或者是请求
Thread.sleep(100);
}
public static void main(String[] args) {
new SimpleTest(5).start();
}
具体的使用也是这么简单。大家可以在实现testThreadMethod来实现自己的压力测试逻辑,比如用httpclient方法一个页面。在代码里面之所以sleep只是防止自旋消耗CPU。可以去掉。有什么可以补充的欢迎讨论!!!