java代码简单实现压力测试
首先,我们使用okhttp,写一个接口调用请求,如下:
private static void postAsync() throws IOException { OkHttpClient client = new OkHttpClient(); final String url = "yourUrl"; RequestBody formBody = new FormBody.Builder() .add("phone", "136XXXXXXXX") .add("verificationCode", "1234") .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if(response.isSuccessful()){ System.out.println(response.body().toString()); }else{ System.out.println(response); } } }); }
然后,我们写一个Runnable的实现类
ublic class Task implements Runnable {private CyclicBarrier cyclicBarrier; private int count; public Task(CyclicBarrier cyclicBarrier,int count) { this.cyclicBarrier = cyclicBarrier; this.count = count; } @Override public void run() { try { // 等待所有任务准备就绪 cyclicBarrier.await(); //测试路径 postAsync(); cyclicBarrier.await(); } catch (Exception e) { System.out.println("出现超时的线程"+count); e.printStackTrace(); } }
最后,我们写一个调用方法
public static void multiRuntime(int count){ int z =0; while(true) { z++; //线程池准备 CyclicBarrier cyclicBarrier = new CyclicBarrier(count); ExecutorService executorService = Executors.newFixedThreadPool(count); long now = System.currentTimeMillis();//开始时间 for (int i = 0; i < count; i++) { executorService.execute(new Task(cyclicBarrier, i)); } executorService.shutdown(); while (!executorService.isTerminated()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } long end = System.currentTimeMillis();//结束时间 System.out.println("第" + z + "批总共耗时!---------" + (end - now));//总共耗时 } }