性能工具之 nGrinder Post 请求脚本

简介: 【5月更文挑战第4天】性能工具之 nGrinder Post 请求脚本

一、前言

在实际压测工作中 Post 请求分为两种最常见传参情况:

  • 第一种是通过 key-value 方式传参数

    • head参数为:Content-Type:application/x-www-form-urlencoded
  • 第二种是通过 Json 方式传参数

    • head参数为:Content-Type:application/json

前置条件是大家源码部署成功的,这样方面咱们直接在源码的脚本位置添加咱们调试的脚本,下面咱们使用两种方式做例子分别介绍。

二、编写测试服务

在模拟请求的服务端的 SpringBoot 工程的 Controller 层添加如下代码:

@PostMapping("/findinfo")
@ResponseBody
public List<UserTable> findUserPost(UserTable userInfo) {
   
    List<UserTable> UserInfo = userService.findinfo(userInfo);
    return UserInfo;
}

如果上面代码看不明白请参考:

三、编写测试脚本

1、key-value 方式

参考代码:

import HTTPClient.Cookie
import HTTPClient.CookieModule
import HTTPClient.HTTPResponse
import HTTPClient.NVPair
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.plugin.http.HTTPRequest
import net.grinder.script.GTest
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import static net.grinder.script.Grinder.grinder
import static org.hamcrest.Matchers.is
// import static net.grinder.util.GrinderUtils.
* // You can use this if you're using nGrinder after 3.2.3
import static org.junit.Assert.assertThat

/**
 * @Title: PostDemo
 * @Description: post请求
 * @author 7DGroup
 * @date 2019/10/24 / 12:22
 */

@RunWith(GrinderRunner)
class PostDemo {
   
    public static GTest test
    public static HTTPRequest request
    public static NVPair[] headers = []
    public static NVPair[] params = []
    public static Cookie[] cookies = []


    @BeforeProcess
    public static void beforeProcess() {
   
        HTTPPluginControl.getConnectionDefaults().timeout = 6000
        test = new GTest(1, "localhost:8888")
        request = new HTTPRequest()

        // Set header datas
        List<NVPair> headerList = new ArrayList<NVPair>()

        //POST key/value格式的params
        headerList.add(new NVPair("Content-Type", "application/x-www-form-urlencoded"))
        headers = headerList.toArray()

        // Set param datas
        List<NVPair> paramList = new ArrayList<NVPair>()
        paramList.add(new NVPair("username", "600128"))
        params = paramList.toArray()
        grinder.logger.info("before process.");
    }


    @BeforeThread
    public void beforeThread() {
   
        test.record(this, "test")
        grinder.statistics.delayReports = true;
        grinder.logger.info("before thread.");
    }


    @Before
    public void before() {
   
        request.setHeaders(headers)
        cookies.each {
    CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
        grinder.logger.info("before thread. init headers and cookies");
    }


    @Test
    public void test() {
   
        HTTPResponse result = request.GET("http://localhost:8888/findinfo", params)
        def text = result.getText()
        grinder.logger.info(text)
        assertThat(result.statusCode, is(200))
    }
}

注意别忘记修改启动参数:

-javaagent:D:\maven\repository\net\sf\grinder\grinder-dcr-agent\3.9.1\grinder-dcr-agent-3.9.1.jar

image.png

点击运行:
image.png

运行结果:
image.png

2、Json 请求方式

在测试前,先模拟可以发送 Json 请求的服务端,在 Controler 层中增加一个方法并且使用可以解析 Json 方法的注解为:@RequestBody

具体代码为:

**
 * json请求
 * @param userInfo
 * @return
 */
@PostMapping("/findinfoJson")
@ResponseBody
public List<UserTable> findUserPostJson(@RequestBody UserTable userInfo) {
   
    List<UserTable> UserInfo = userService.findinfo(userInfo);
    return UserInfo;
}

通过上面代码调整即可接受 Json 格式的请求,以下通过源码编写脚本;

import HTTPClient.Cookie
import HTTPClient.CookieModule
import HTTPClient.HTTPResponse
import HTTPClient.NVPair
import net.grinder.plugin.http.HTTPPluginControl
import net.grinder.plugin.http.HTTPRequest
import net.grinder.script.GTest
import net.grinder.scriptengine.groovy.junit.GrinderRunner
import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess
import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import static net.grinder.script.Grinder.grinder
import static org.hamcrest.Matchers.is
// import static net.grinder.util.GrinderUtils.*
// You can use this if you're using nGrinder after 3.2.3
import static org.junit.Assert.assertThat

/**
 * @Title: PostDemo
 * @Description: json请求
 * @author 7DGroup
 * @date 2019/10/24 / 12:22
 */

@RunWith(GrinderRunner)
class PostDemo {
   
    public static GTest test
    public static HTTPRequest request
    public static NVPair[] headers = []
    public static NVPair[] params = []
    public static Cookie[] cookies = []

    @BeforeProcess
    public static void beforeProcess() {
   
        HTTPPluginControl.getConnectionDefaults().timeout = 6000
        test = new GTest(1, "localhost:8888")
        request = new HTTPRequest()
        // Set header datas
        List<NVPair> headerList = new ArrayList<NVPair>()
        headerList.add(new NVPair("Content-Type", "application/json"))
        headers = headerList.toArray()
        grinder.logger.info("before process.");
    }


    @BeforeThread
    public void beforeThread() {
   
        test.record(this, "test")
        grinder.statistics.delayReports = true;
        grinder.logger.info("before thread.");
    }


    @Before
    public void before() {
   
        request.setHeaders(headers)
        cookies.each {
    CookieModule.addCookie(it, HTTPPluginControl.getThreadHTTPClientContext()) }
        grinder.logger.info("before thread. init headers and cookies");
    }


    @Test
    public void test() {
   
        String url = "http://localhost:8888/findinfoJson"
        String parambody = "{\"username\":\"600128\"}"
        HTTPResponse result = request.POST(url, parambody.getBytes())

        //显示结果
        def text = result.getText()
        grinder.logger.info(text)
        assertThat(result.statusCode, is(200))
    }
}

运行结果:
image.png

四、源码分析

通过点击方法的 post 请求可以看出源码中支持那些方式传参:

HTTPResponse result = request.POST(url, parambody.getBytes())

image.png

五、总结

注意 key-value与 Json 在传参的时候注意 Content-Type 的值就行。

源码地址:

目录
相关文章
|
9月前
|
存储 弹性计算 固态存储
阿里云服务器2核8G、4核16G、8核32G租用价格:2026最新收费标准活动价格参考
阿里云2026年提供的2核8G、4核16G、8核32G服务器配置,能满足不同场景需求。其价格因实例规格、所选地域、系统盘类型、容量、公网带宽等因素而异,且受包年包月和按量付费两种模式影响。面对众多实例,用户可从预算、性能需求和业务场景三个维度考量,选择最适合自己的实例。此外,用户还可根据账号实名认证情况领取阿里云优惠券,降低购买成本。
1289 1
|
5月前
|
人工智能 安全 数据管理
Gartner:2026年数据与分析顶级趋势
Gartner发布的2026年数据与分析顶级趋势报告显示,AI智能体、语义层进步以及数据与分析平台的融合,将成为引领未来发展的三大核心趋势。对于希望识别关键业务和技术主题的数据与分析(D&A)领导者而言,这些领域是实现高性价比价值、更快成为AI FIRST企业的关键。
|
8月前
|
机器学习/深度学习 人工智能 图形学
🦞快在轻量化服务器上部署你的视觉龙虾吧——支持视觉识别到3D打印
彭博士打造的“视觉龙虾”系统,融合多视角3D重建、点云深度学习与参数化建模,支持手机拍照或自然语言输入,秒级生成可3D打印的STL模型。依托OpenClaw智能编排与阿里云轻量化部署,真正实现“想法→照片/文字→3D模型→实物”的端到端闭环,让3D打印零门槛。(239字)
1073 9
🦞快在轻量化服务器上部署你的视觉龙虾吧——支持视觉识别到3D打印
|
前端开发 Java 数据库连接
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
|
10月前
|
人工智能 弹性计算 安全
2026年阿里云一键部署OpenClaw的五种方案,快速拥有专属AI助手!
OpenClaw(原Clawdbot/Moltbot)是开源本地优先AI代理平台,支持文档撰写、资料检索、日程安排等真实任务执行。阿里云提供5种一键部署方案——轻量服务器、无影企业/个人版、AgentBay SDK、ECS+计算巢,最快5分钟上线,适配个人至企业全场景,隐私安全、开箱即用。
890 6
|
编解码 网络协议
如何轻松地 rip 3D Blu-ray:详细步骤指南
随着3D电影和家庭影院的普及,越来越多的人希望将3D Blu-ray电影转换为数字文件,以便在多种设备上播放。本文介绍了使用DVDFab、MakeMKV+HandBrake和Leawo Blu-ray Ripper等软件轻松rip 3D Blu-ray的方法,帮助用户享受高质量的3D观影体验。这些工具不仅提供了便捷性和高质量的输出,还能节省存储空间。
1754 9
|
12月前
|
传感器 人工智能 算法
智能之巅:AI 如何重塑第六代战斗机
近日,两架“歼-36”六代机在成都双机同框引发热议。这不仅是航空技术的突破,更标志着AI深度融入空战体系。从群体智能到“忠诚僚机”,AI正重塑战争逻辑,推动中国空军迈向“算法为王”的智能时代。
826 0
|
人工智能 算法 机器人
西安交通大学AI Day成功举办:产教融合共育人工智能时代新人才丨云工开物
10月29日,西安交大计算机学院联合阿里云成功举办首届“AI Day”,涵盖“AI+X”产学研讨会与“0基础玩转大模型”学生训练营,推动产教融合,共探人工智能时代教育变革与人才培养新路径。
|
Prometheus 监控 Cloud Native
78_资源监控:NVIDIA-SMI进阶
在大语言模型(LLM)训练和推理过程中,GPU资源的高效监控和管理至关重要。随着模型规模的不断增长和计算需求的提升,如何精确监控GPU利用率、及时发现性能瓶颈并进行优化,成为AI研究人员和工程师面临的重要挑战。NVIDIA-SMI作为NVIDIA官方提供的GPU监控工具,提供了丰富的功能来监控和管理GPU资源。本文将深入探讨NVIDIA-SMI的进阶使用方法,以及如何利用其与其他工具结合构建高效的GPU利用率可视化监控系统。
1570 0
|
Java 测试技术 编译器
@GrpcService使用注解在 Spring Boot 中开始使用 gRPC
本文介绍了如何在Spring Boot应用中集成gRPC框架,使用`@GrpcService`注解实现高效、可扩展的服务间通信。内容涵盖gRPC与Protocol Buffers的原理、环境配置、服务定义与实现、测试方法等,帮助开发者快速构建高性能的微服务系统。
2139 0

热门文章

最新文章