000--并发测试

  • 参考网址:https://www.jianshu.com/p/924dc048515b

1、常用的三种并发测试方法

  • PostMan
  • JMeter
  • Java代码

2、Java代码并发测试

  • 2.1)添加依赖
        
            org.apache.httpcomponents
            httpclient
            4.0.2
            test
        
  • 2.2)创建Java类(这样的结果是不正确的)
@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 Exception {
        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) {
                    System.out.println("exception:"+e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("count:"+count);
    }

    private static void add() {
        count++;
    }
}

-最简单的并发测试(使用原子变量进行数据打印【切记】)

@RunWith(SpringRunner.class)
@SpringBootTest
public class SeckillApplicationTests {

    public static final String SKU = "iPhone7";
    public static int UserCount = 5;
    public static int UserBuyCount = 3;
    public static AtomicInteger userSuccessCount = new AtomicInteger();
    public static AtomicInteger stackSuccessCount = new AtomicInteger();

    @Resource
    KillService killService;
    @Test
    public void contextLoads() {
        boolean flag = killService.updateGoodsCount(1, SKU);
        System.out.println("------------------数据更新成功:"+flag);
    }

    @Test
    public void contextLoadsThread() throws InterruptedException {
        for (int i = 0; i < UserCount; i++) {
            Thread task = new Thread() {
                @Override
                public void run() {
                    if (killService.updateGoodsCount(UserBuyCount, SKU)){
                        System.out.println("------------------数据更新成功");
                        userSuccessCount.incrementAndGet();//购买成功用户加一
                        stackSuccessCount.addAndGet(UserBuyCount);//购买成功商品
                    }else {
                        System.out.println("------------------数据更新失败");
                    }
                }
            };
            task.start();
            task.join();
        }
        System.out.println("------------------购买成功人数:"+userSuccessCount);
        System.out.println("------------------购买成功商品:"+stackSuccessCount);
    }
}

你可能感兴趣的:(000--并发测试)