其實就是用CountDownLatch來使多個線程同時運行,同時發送請求,雖然post的事件不能保證同時,但發post能保證同時(相差0.2毫秒),通過這種方法,測試了redis的setkey,getkey來保證不重複數據的時間閾值在幾百納秒,再短就算redis也無能爲力了,所以多線程雖然快,但是沒鎖,還是不太安全。。
@Service
public class TestConcurrentService {@Autowired
private ApiHttpClientService apiHttpClientService;
private static final Logger logger = Logger.getLogger(TestConcurrentService.class);
public void testConcurrent1(String sign) {
ExecutorService exec = Executors.newFixedThreadPool(3);
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
exec.execute(new HttpRequestUtils(begin, end, sign));
}
begin.countDown();
try {
end.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
exec.shutdown();
logger.info("main method end");
}
public class HttpRequestUtils implements Runnable {
private Logger log = Logger.getLogger(HttpRequestUtils.class);
private CountDownLatch begin;
private CountDownLatch end;
private String sign;
private String url = "http://localhost:8080/score/private/v1/injectsg";
public HttpRequestUtils(CountDownLatch begin, CountDownLatch end, String sign) {
this.begin = begin;
this.end = end;
this.sign = sign;
}
@Override
public void run() {
try {
begin.await();
Map<String, String> header = new HashMap<>();
header.put("Content-Type", "application/json");
header.put("sign", sign);
ScoreRequestBean bean = new ScoreRequestBean();
Data data = new Data();
data.setRemark("單發測試");
data.setExtId("ext111111519");
data.setPartnerMemberId(297);
data.setPoints(1);
bean.setData(data);
bean.setEventId("123asdasd");
System.out.println("線程" + Thread.currentThread().getName() +
"已接受命令," + "時間爲:" + System.nanoTime() + "|" + System.nanoTime() / 1000000L);
apiHttpClientService.post(url, null, header, bean, ResultConstant.class);
System.out.println("線程" + Thread.currentThread().getName() +
"命令已結束");
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
end.countDown();
}
}
}
}