【高併發】02 併發工具測試類

1、Postman:模擬Http請求

2、Apache Bench(AB): Apache 附帶的工具,測試網站性能

# ab -n 1000 -c 50 http://localhost:8080/hello

-n: 併發總數

-c: 允許一次請求併發數

3、JMeter: Apche 組織開發的壓力測試工具

4、代碼測試: 結合Semaphore、CountDownLatch

package com.current.flame.test;

import com.current.flame.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author haoxiansheng
 */
@Slf4j
@NotThreadSafe
public class ConcurrencyTest {
    // 請求總數
    public static int clientTotal = 5000;

    // 允許同時執行的線程併發數
    public static int threadTotal = 200;

    public static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(threadTotal); // 信號量 允許有多少個同時執行
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); // 閉鎖
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.info("e=>{}", e.getMessage());
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        log.info("count==>{}", count);
        executorService.shutdown();
    }

    /**
     * 這是不安全的 加synchronized
     */
    private static void add() {
        count++;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章