java code is a simple implementation of stress tests

First, we use okhttp, write a call request interface, as follows:

   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);
                }

            }
        });
    }

Then, we write a class that implements the 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 () {
         the try {
             // wait for all tasks Ready 
            CyclicBarrier.await ();
             // test path 
            postAsync ();
            cyclicBarrier.await();
        } catch (Exception e) {
            System.out.println ( "timeout thread" + COUNT);
            e.printStackTrace ();
        }
    }

Finally, we write a method call

public static void multiRuntime(int count){
        int z =0;
        while(true) {

            z ++ ;
             // thread pool ready 
            CyclicBarrier CyclicBarrier = new 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 (); // End Time 
            System.out.println ( "first" + z + "Batch took a total ---------!" + (End - now)); / / took a total 
        }
    }

 

Guess you like

Origin www.cnblogs.com/fbw-gxy/p/11762506.html