CountDownLatch模拟多用户并发访问

需求:测试项目部署的kafka能同时处理多少并发请求

代码:首先创建用户线程类,run方法中编写测试内容,这里因为是ssm项目,直接就在structs中的action类中写了一个test方法

package com.besto.authbilling.po;

import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;


import cn.com.besto.util.HttpClientUtil;



public class UserDemo implements Runnable{
	private String url;
	private static Logger logger = Logger.getLogger(UserDemo.class); 
	private static CountDownLatch begin;
	
	public UserDemo(String url, CountDownLatch begin) {
		this.url = url;
		UserDemo.begin = begin;
	}

	
	public String getUrl() {
		return url;
	}


	public void setUrl(String url) {
		this.url = url;
	}


	public CountDownLatch getBegin() {
		return begin;
	}


	public void setBegin(CountDownLatch begin) {
		UserDemo.begin = begin;
	}


	@Override
	public void run() {
		try {
			logger.debug("用户"+Thread.currentThread().getName()+"初始化完成");
			begin.await();//线程开始等待
			logger.debug("用户"+Thread.currentThread().getName()+"开始执行");
			String ret=HttpClientUtil.getHttpClientInfo(this.getUrl());//这里换成要测试的逻辑
			logger.debug("用户"+Thread.currentThread().getName()+"结束执行");
			logger.debug("用户"+Thread.currentThread().getName()+"执行结果是"+ret);
		} catch (InterruptedException e) {
			logger.debug("错误信息:"+e.getMessage());
		}
	}
	
}

public String test() throws Exception{
		//...省略一部分代码
		CountDownLatch begin = new CountDownLatch(1);
		for(int i=0;i<600;i++){
			String str=AESUtil.encrypt(params1+r.nextLong()+params2);
			logger.debug("加密后字符串>>>>>>>"+str);
			UserDemo user=new UserDemo(str1+"&userid="+list.get(i).toString()+str2+"¶ms="+str,begin);//创建线程类
			Thread test=new Thread(user, "user"+list.get(i).toString());//创建线程
			test.start();
		}
		begin.countDown();//线程开始执行
		return null;
	}

你可能感兴趣的:(JavaWeb)