批量获取1000个用户token,并使用jmeter进行压力测试(黑马点评之秒杀优化)
·
前置准备
- 往数据库中插入1000个用户(删除了可以在课程资料sql文件中找)

- 添加秒杀优惠券:(因为没有后台,所以直接在postman上传)

{
"shopId": 1,
"title": "100元代金券",
"subTitle": "周一至周五均可使用",
"rules": "全场通用\\n无需预约\\n可无限叠加\\不兑现、不找零\\n仅限堂食",
"payValue": 8000,
"actualValue": 10000,
"type": 1,
"stock": 100,
"beginTime": "2022-08-09T10:25:01",
"endTime": "2025-08-10T10:25:01"
}
- 订单表清空,库存改为200和课程保持一致
批量生成token
生成1000个token保存到Redis并写入tokens.txt文件
思路:由于token只保存在Redis中,直接将随机生成的token批量保存到Redis中,并写入tokens.txt文件
方法:根据之前的用户登录生成token保存到Redis的代码,稍作修改即可
- 代码实现:
package com.hmdp;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.service.IUserService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.*;
@SpringBootTest
public class GetTokensAndWriteFiles {
@Resource
private IUserService userService;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Test
void getTokensAndWriteFiles() throws IOException {
//查询用户信息 限制1000个
List<User> users = userService.lambdaQuery().last("limit 1000").list();
FileWriter fr = null;
try {
//文件位置
fr = new FileWriter("D:\\myidea\\code\\tokens.txt");
//遍历每一个用户,并生成token
for (User user : users) {
//保存用户信息到 Redis 中
//随机生成 token 作为登录令牌
String token = UUID.randomUUID().toString(true);
//将 user 对象 转化为 hashmap 存储
UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
//字段名 字段值的类型都改成 String
//userDTO有Long id 需要字段值转换,通过setFieldValueEditor配置
Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,
new HashMap<>(),
CopyOptions.create()
.setIgnoreNullValue(true)
.setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
//存储
String tokenKey = LOGIN_USER_KEY + token;
stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
//设置 token 有效期
stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
//将Redis中token写入文件中
fr.append(token);
fr.append("\n");
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
fr.close();
}
}
}
-
启动测试
发现Redis和token.txt文件都有数据了

如果token显示的没有1000个login:token,可能设置的加载数量小了,修改即可。
jmeter压测
根据课程配置好jmeter
-
登录状态头

-
tokens文件(文件名路径修改成自己的)

-
http请求秒杀优惠券路径

配置完,根据课程视频所讲启动测试即可。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)