public class ConcurrentInvoiceTest { final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { CountDownLatch latch=new CountDownLatch(1); for(int i=0;i<20;i++){//模拟20个用户 AnalogUser analogUser = new AnalogUser("user"+i,"50",latch); analogUser.start(); } latch.countDown();//计数器減一 所有线程释放 并发访问。 System.out.println("所有模拟请求结束 at "+sdf.format(new Date())); } static class AnalogUser extends Thread { String workerName;//模拟用户姓名 String newReadInvoiceNum; CountDownLatch latch; public AnalogUser(String workerName, String newReadInvoiceNum, CountDownLatch latch) { this.workerName = workerName; this.newReadInvoiceNum = newReadInvoiceNum; this.latch = latch; } @Override public void run() { // TODO Auto-generated method stub try { latch.await(); //一直阻塞当前线程,直到计时器的值为0 } catch (InterruptedException e) { e.printStackTrace(); } boolean flag= post();//发送post 请求 System.out.println( "flag=="+flag); } public boolean post() { String path = "http://localhost:8080/query"; Map<String, String> params = new HashMap<String, String>(); params.put("newReadInvoiceNum", newReadInvoiceNum); try { return sendHttpClientPOSTRequest(path, params, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return false; } private static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{ List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数 if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding); HttpPost httpPost = new HttpPost(path); httpPost.setEntity(entity); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpPost); if(response.getStatusLine().getStatusCode() == 200){ return true; } return false; } } }
模拟并发用户发送请求
猜你喜欢
转载自blog.csdn.net/thedarkclouds/article/details/80650883
今日推荐
周排行