黑马程序员Redis入门到实战教程,深度透析redis底层原理+redis分布式
2023-08-05 17:15 作者:bili_48232325622 | 我要投稿

P69 回应下面的兄弟,Jmeter批量登陆测试,是直接接口测试,看看拦截器就知道了(代码在下方)
只需要redis中hashMap如下格式:Key:RedisConstans.LOGIN_TOKEN_KEY + token
value:用户信息(UserDTO)
就没问题了。
代码如下:
@Test public void bulkLogin() { //查询所有用户 List<User> users = userService.list(); //获取resource目录下的文件路径(用于存放生成的token) String path = new File("").getAbsolutePath() + "\\src\\main\\resources\\tokens.txt"; //String file = Objects.requireNonNull(BulkLogin.class.getClassLoader().getResource("tokens.txt")).getFile(); //创建字符写入流 FileWriter fw = null; try { fw = new FileWriter(path); } catch (IOException e) { throw new RuntimeException(e); } //创建字符写入缓冲区 BufferedWriter bw = new BufferedWriter(fw); users.forEach(user -> { //8.保存用户信息到redis中 //8.1随机生成token作为登录令牌 String token = UUID.randomUUID().toString(); //8.2将user对象转为hashMap存储 UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class); Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create() .setIgnoreNullValue(true) .setFieldValueEditor((field, fieldValue) -> fieldValue.toString()) ); //System.out.println(map); //导入redis stringRedisTemplate.opsForHash().putAll(RedisConstans.LOGIN_TOKEN_KEY + token, map); //设置有效期,30分钟 stringRedisTemplate.expire(RedisConstans.LOGIN_TOKEN_KEY, 30, TimeUnit.MINUTES); //这一行代码是同时获取Map中的key和value,当然和这个批量登陆功能没关系 //Set<Map.Entry<String, Object>> set = map.entrySet(); try { //开始写入 bw.write(token + "\n"); //强制刷新 bw.flush(); } catch (IOException e) { throw new RuntimeException(e); } }); System.out.println("运行成功!"); }