1、写作背景
在进行秒杀的时候设置了单用户不能进行重复秒杀的规则,所以在进行秒杀的时候要模拟多用户场景
2、学习目的
- 模拟多用户参数
- 模拟秒杀场景
- 避免超卖现象
3、数据准备
多用户模拟,要在数据库创建用户(手机号)
返回对应的token,和手机号进行一对一记录,生成JMeter的参数配置文件
创建一个UserUtils工具类,进行用户创建和模拟登陆
public class UserUtil {
private static void createUser(int count) throws Exception{
List<LoginUser> users = new ArrayList<>(count);
//生成用户
for(int i=0;i<count;i++) {
LoginUser user = new LoginUser();
user.setId(13000000000L+i);
user.setLoginCount(1);
user.setNickname("user"+i);
user.setRegisterDate(new Date());
user.setSalt("1a2b3c");
user.setPassword(MD5Utils.inputPassToDbPass("123456", user.getSalt()));
users.add(user);
}
System.out.println("create user");
//插入数据库
// Connection conn = DBUtil.getConn();
// String sql = "insert into login_user(loginCount, nickname, registerDate, salt, password, id)values(?,?,?,?,?,?)";
// PreparedStatement pstmt = conn.prepareStatement(sql);
// for(int i=0;i<users.size();i++) {
// LoginUser user = users.get(i);
// pstmt.setInt(1, user.getLoginCount());
// pstmt.setString(2, user.getNickname());
// pstmt.setTimestamp(3, new Timestamp(user.getRegisterDate().getTime()));
// pstmt.setString(4, user.getSalt());
// pstmt.setString(5, user.getPassword());
// pstmt.setLong(6, user.getId());
// pstmt.addBatch();
// }
// pstmt.executeBatch();
// pstmt.close();
// conn.close();
// System.out.println("insert to db");
//登录,生成token
String urlString = "http://localhost:9091/login/do_login";
File file = new File("C:\\TT_Enzoism+\\tokens.txt");
if(file.exists()) {
file.delete();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
file.createNewFile();
raf.seek(0);
for(int i=0;i<users.size();i++) {
LoginUser user = users.get(i);
URL url = new URL(urlString);
HttpURLConnection co = (HttpURLConnection)url.openConnection();
co.setRequestMethod("POST");
co.setDoOutput(true);
OutputStream out = co.getOutputStream();
String params = "mobile="+user.getId()+"&password="+MD5Utils.inputPassToFormPass("123456");
out.write(params.getBytes());
out.flush();
InputStream inputStream = co.getInputStream();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int len = 0;
while((len = inputStream.read(buff)) >= 0) {
bout.write(buff, 0 ,len);
}
inputStream.close();
bout.close();
String response = new String(bout.toByteArray());
JSONObject jo = JSON.parseObject(response);
String token = jo.getString("data");
System.out.println("create token : " + user.getId());
String row = user.getId()+","+token;
raf.seek(raf.length());
raf.write(row.getBytes());
raf.write("\r\n".getBytes());
System.out.println("write to file : " + user.getId());
}
raf.close();
System.out.println("over");
}
public static void main(String[] args)throws Exception {
createUser(5000);
}
}
- 在JMeter中导入配置用户信息,然后进行
- 执行结果有点搞笑了,超卖,这个就是我们要解决的事情