使用多线程的方式模拟高并发请求接口,用于自测接口的稳定性【项目】

java 复制代码
 package com.gitee.taven.test;

import com.gitee.taven.ApiResult;
import com.gitee.taven.aop.RepeatSubmitAspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class RunTest implements ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RunTest.class);

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("执行多线程测试");
        String url="http://localhost:8080/submit";
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for(int i=0; i<10; i++){
            String userId = "userId" + i;
            HttpEntity request = buildRequest(userId);
            executorService.submit(() -> {
                try {
                    countDownLatch.await();
                    System.out.println("Thread:"+Thread.currentThread().getName()+", time:"+System.currentTimeMillis());
                    ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
                    System.out.println("Thread:"+Thread.currentThread().getName() + "," + response.getBody());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        countDownLatch.countDown();
    }

    private HttpEntity buildRequest(String userId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "yourToken");
        Map<String, Object> body = new HashMap<>();
        body.put("userId", userId);
        return new HttpEntity<>(body, headers);
    }

}

        countDownLatch.countDown();
    }
相关推荐
逑之15 分钟前
C语言笔记5:函数
java·c语言·笔记
无限进步_17 分钟前
【C语言&数据结构】对称二叉树:镜像世界的递归探索
c语言·开发语言·数据结构·c++·git·算法·visual studio
JavaLearnerZGQ20 分钟前
1、Java中的线程
java·开发语言·python
小当家.10532 分钟前
深入理解JVM:架构、原理与调优实战
java·jvm·架构
刀法如飞40 分钟前
一款开箱即用的Spring Boot 4 DDD工程脚手架
java·后端·架构
一嘴一个橘子44 分钟前
spring-aop 的 基础使用 -3 - 切点表达式 的提取、复用
java
Re_zero1 小时前
Java新手避坑:为什么我劝你放弃 scanner.nextInt()?
java
玖剹1 小时前
队列+宽搜(bfs)
数据结构·c++·算法·leetcode·宽度优先
Good_Starry1 小时前
Java——反射
java