压测工具类

package com.wangyin.th.wallet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : test
 * @date : 2020/6/12 09:27
 */
public class PerformanceTestUtils {
    private static Logger log = LoggerFactory.getLogger(PerformanceTestUtils.class);
    public static final AtomicInteger success = new AtomicInteger(0);
    public static final AtomicInteger fail = new AtomicInteger(0);

    public static void success() {
        success.incrementAndGet();
    }

    public static void fail() {
        fail.incrementAndGet();
    }

    static {
        new Timer("tps-monitor").schedule(new TimerTask() {
            int prevSuc = 0;
            int prevFail = 0;

            @Override
            public void run() {
                int currentSuc = success.get();
                int currentFail = fail.get();
                log.info("TPS:成功={}, 失败={}", currentSuc - prevSuc, currentFail - prevFail);
                prevSuc = currentSuc;
                prevFail = currentFail;
            }
        }, 1000, 1000);
    }

    public static void execute(int nthread, int tps, Command command) {
        ExecutorService executorService = new ThreadPoolExecutor(nthread, nthread, 1000, TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(10000), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());
        while (true) {
            for (int i = 0; i < tps; i++) {
                executorService.execute(() ->
                {
                    try {
                        command.execute();
                        success();
                    } catch (Exception e) {
                        fail();
                    }
                });
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 失败请抛异常
     */
    public interface Command {
        void execute() throws Exception;
    }
}

 

你可能感兴趣的:(java编程实践)