Performance Test 1: Performance Theory and JMeter Use

1. Performance testing theory

1.1 What kind of system needs performance testing?

  1. A system with a large number of users and high PV
  2. System core modules/interfaces
  3. Business logic/algorithm is relatively complex
  4. Promotion/event promotion plan
  5. New systems, new projects
  6. Verification and tuning of online performance issues
  7. New technology selection
  8. Performance capacity assessment and planning (for capacity assessment, estimate specific capacity)
  9. Daily system performance regression

1.2 Performance test indicators

  1. affairs
  • In the field of performance testing, measuring the performance of a system mainly depends on how much business the system can handle per unit time.
  • A transaction represents a business operation. A transaction can represent a business or multiple business operations.
  1. TPS/QPS: Number of transactions processed per second
  2. Response time
  • Response time = total network transmission time + business processing time of each component

image.png

  • Average response time: the average time taken by all requests during the test. (PS: When the number of samples is small, if you use the average value to look at the data, the conclusion will be abnormal. For example, if one interface is 1ms and another interface is 1s, the average value is unreasonable)
  1. TOP response time
  • Tp90 (90% response time): 90% of requests take less than a certain time
  • Tp95 (95% response time): 95% of requests take less than a certain time
  • Tp99 (99% response time): 99% of requests take less than a certain time
  • Algorithm: Sort the response times of all requests from large to small, and calculate the specified proportion of requests that are less than a certain time. This metric measures the time taken by most requests.

Take Tp90 as an example

Interface A responds 10 times continuously Request serial number Response time ms
1 800
2 600
3 500
4 900
5 950
6 750
7 400
8 500
9 300
10 500

Step 1: Sort the list in descending order

Interface A responds 10 times continuously Request serial number Response time ms
5 950
4 900
1 800
6 750
2 600
3 500
8 500
10 500
7 400
9 300

90%*10=9, from the last to the ninth are all below 900ms, so 900ms is used as the dividing line

  1. The general response time of high-frequency interfaces is 200ms, and the general response time of low-frequency interfaces is 100ms. The high-frequency interfaces need to be optimized; static resources do not need to be tested and are all stored in CDN.
  2. Number of concurrency/virtual users: the number of concurrent threads/processes set in the stress testing tool
  3. Success rate: The success rate of the request
  4. PV (Page View): the number of visits to the page/interface
  5. UV (Unique Visitor): the daily unique visitor of the page/interface
  6. Throughput: the sum of upstream and downstream traffic in the network
  • Throughput represents the traffic of the network. The higher the TPS (requests per second), the greater the throughput.

1.2.1 The relationship between TPS, response time and number of concurrencies

  • Before the system reaches a performance bottleneck, TPS is directly proportional to the number of concurrencies.
  • Response time (unit: seconds) is the premise:
    • TPS = 1 / response time * number of concurrencies
    • TPS = number of concurrencies/response time
      • After running the performance test, you can calculate the TPS from the results. If the values ​​are not much different, the results are appropriate.
      • If there are multiple interfaces concurrently, the response time of each interface needs to be added up.
    • image.png

1.3 Performance monitoring indicators

  1. Operating system monitoring level
  • CPU usage, memory usage, network IO (input/output), disk (read/write/util)
  1. Middleware monitoring
  • Number of connections, long and short connections, memory usage
  1. Application layer monitoring
  • Thread status, JVM parameters, GC frequency, locks
  1. db layer monitoring
  • Number of connections, locks, cache, memory, SQL efficiency

1.4 Performance testing process

  1. requesting research
    1. Research scope
      • Background of the project
      • Test Range
      • Business logic & data flow direction (data: where does the data come from, is there any cache, and whether to call third-party interfaces, understanding this will help troubleshoot problems)
      • System architecture (deployed architecture and components used, such as load balancing, message middleware, load balancing, etc.)
      • Configuration information (hardware configuration, such as CPU cores and memory, some companies will have performance testing environments, try to keep them consistent with online)
      • Amount of test data (the magnitude must be consistent)
      • external dependencies (mock)
      • System usage scenarios, business ratio (such as login and registration interfaces, real scenarios will definitely have simultaneous scenarios, then the business ratio can be understood as how many people log in and how many people register at the same time)
      • Daily Business Volume (PV)
      • expected indicators
      • time online
  2. Test Plan
    1. project description
    2. Business model and performance indicators (expected indicators in demand research)
    3. Test environment description
    4. test resources
    5. Testing methods and scenario design principles
      • Benchmark test: In order to find a performance benchmark, it is usually a series of operations that are run concurrently and for a long time; meaning: by comparing the data after optimizing the interface with the data before optimization, you can see the optimization effect; but if you want to see the performance inflection point , still need to use high concurrency for pressure testing
      • Single transaction load test (commonly used) : refers to the test of single business and single interface
      • Mixed scenario testing (commonly used) : For example, login and registration interfaces, be sure to run a single transaction load test first to ensure that there are no problems with each interface, and then conduct stress testing according to a certain ratio (obtained from the demand survey)
      • High availability testing (generally for online clusters)
        • Test method: Hang up a node in the cluster to see if the cluster can run normally; run the hung node again to see if the cluster can be used normally after the node is restarted.
      • Abnormal scenario testing: For example, in a weak network scenario, when sending a request, although the network is weak, high concurrency will still occur; there are some abnormal situations, such as transactions under a weak network, and the interface does not run through the first time because certain triggers are triggered. mechanism and re-run the interface, which may result in two orders being generated.
      • Stability test (commonly used) : A long-term stress test (such as 12 hours) is required to test whether there are problems such as memory leaks, etc.
      • Other special scenes
  3. Environment setup hardware configuration
    1. Precautions
      • Try to be consistent with online
      • The system version is consistent with the online version
      • Test environment deploys the smallest online unit module
      • Application, middleware, and database configurations must be consistent with those online
      • Other special configuration
  4. data preparation
    1. Test data is divided into: basic data, parameterized data
    2. Data construction method:
    • business interface
      • Suitable for complex data table relationships
      • Advantages: better data integrity
    • stored procedure
      • Suitable for small number of tables and simplicity
      • Pros: Fastest
    • script import
      • Suitable for complex data logic
      • relatively high degree of freedom
  5. Scripting
    1. Choose a tool (Loadrunner, Jmeter, Locust, etc.)
    2. Select protocol (HTTP, TCP, RCP)
    3. to parameterize
    4. association
    5. checking point
    6. business judgment
  6. Pressure test execution
    1. distributed execution
    2. monitor
      • Linux
      • JVM
      • database
    3. Mobile Test Results
    4. data analysis
    5. Bottleneck location
  7. tuning regression
    1. Performance tuning needs to be done by the whole team
    2. try again and again
    3. regression validation
    4. monitoring tool
    5. Full Link Troubleshooting
    6. log analysis
    7. module isolation
  8. testing report

1.5 HTTP protocol

1.5.1 Introduction to http

1. Support client/server mode.
2. Simple and fast: When a client requests services from the server, it only needs to transmit the request method and path. Commonly used request methods include GET, POST, PUT, and DELETE. Each method specifies a different type of contact between the client and the server.
Due to the simplicity of the HTTP protocol, the program size of the HTTP server is small and the communication speed is very fast.
3. Flexible: HTTP allows the transmission of any type of data object. The type being transferred is marked by Content-Type.
4. No connection: The meaning of no connection is to limit each connection to only process one request. After the server processes the client's request and receives the client's response, it disconnects. In this way, transmission time can be saved.
5. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory ability for transaction processing. The lack of status means that if subsequent processing requires the previous information, it must be retransmitted, which may result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it does not need previous information.

1.5.2 http protocol structure


tips:

Questions about the distinction between the concepts of stress testing, load testing, and performance testing
1. There is no unified standard or definition in the industry for the above three concepts. There are various materials and different explanations.
2. For beginners, you can ignore these concepts for now
. 3 . Just remember: all the tests you do become performance tests. In actual companies, they are called [stress tests]
4. As for whether it is to test the maximum concurrent users, stability, or the highest tps, these are all performance tests, just tests. The purposes are different, and different test scenarios are designed because of the different purposes.

2.Jmeter

2.1 Installation and configuration

Official website: https://jmeter.apache.org/
1. Configure Java environment variables on this machine
2. Download the compressed package from the official website and unzip it in any directory
3. Modify the configuration file and open jmeter.properties in Jmeter's bin directory. Modify
language=zh_CN #Chinese and English environment
sampleresult.default.encoding=utf-8 #Prevent garbled characters

Adjust icon size
jmeter.toolbar.icons.size=32x32
jmeter.tree.icons.size=32x32

Modify message body data size
jsyntaxtextarea.font.family= Hack
jsyntaxtextarea.font.size=36

Change the size of the interface element
to true to enable
jmeter.hidpi.mode=true
to control the size
jmeter.hidpi.scale.factor=2.0

If the modified configuration does not take effect, add the following code to jmeter.bat
image.png

set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.controlFont=Dialog-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.systemFont=Dialog-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.userFont=SansSerif-20
set JVM_ARGS=%JVM_ARGS% -Dswing.plaf.metal.smallFont=SansSerif-20

4. Enter the bin directory of Jmeter and double-click jmeter.bat to start

2.2 Scripting

2.2.1 Entry

Three types of input

Interface name Interface Type parameter
The parameter is key=value POST username=“123”&password=“123”
The parameter is of json type POST {username=“123”,password=“123”}
The parameter is key=json type POST key = {username=“123”,password=“123”}

The second type: json type.
image.png
The input parameters of json type are filled in [Message Body Data]. If the message body data has data, [Parameter] cannot be operated. Note: If the
parameter is of json type , an http information header needs to be added for management . When configuring the component, you should also pay attention to the effective domain of the configuration component. Not all input parameters of the interface may be of this type. image.png
HTTP header management:
image.png
PS: If a 415 error is reported, check whether the header is added.

The third method: key=json type
convenient method: you can paste directly from the [Add from Clipboard] at the bottom
image.png

2.2.2 Assertion

The success status viewed in the result tree is only that the interface call was successful (because respond code=200), but it cannot be judged whether the business has run through, so an assertion needs to be added.

2.2.2.1 JSON assertion

1. Add assertion:
JSON path expression: $.code represents the code field name in JSON (detailed reference: https://github.com/json-path/JsonPath)
You need to check additionally assert value, match as regular expression
image.png
PS : Assertion also pay attention to the location where the assertion file is stored. The storage level is different, and the effective domain is different. For example, if it is stored under the login interface on the way, it will only take effect on the login interface. If it is placed on the outermost layer, it will take effect on the entire domain.image.png

2. JSON contains arrays , which can be processed as follows:
Example json:

{
    
    
  "store": {
    
    
    "book": [
      {
    
    
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
    
    
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
    
    
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
    
    
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
    
    
      "color": "red",
      "price": 19.95
    }
  },
  "expensive": 10
}

Processing method:

JsonPath Result
$.store.book[*].author The authors of all books
$…author All authors
$.store.* All things, both books and bicycles
$.store…price The price of everything
$…book[2] The third book
$…book[-2] The second to last book
$…book[0,1] The first two books
$…book[:2] All books from index 0 (inclusive) until index 2 (exclusive)
$…book[1:2] All books from index 1 (inclusive) until index 2 (exclusive)
$…book[-2:] Last two books
$…book[2:] All books from index 2 (inclusive) to last
$…book[?(@.isbn)] All books with an ISBN number
$.store.book[?(@.price < 10)] All books in store cheaper than 10
Misplaced @

$…book[?(@.price <= $[‘expensive’])] | All books in store that are not “expensive” |
| $…book[?(@.author =~ /.REES/i)] | All books matching regex (ignore case) |
| $…
| Give me every thing |
| $…book.length() | The number of books |

2.2.2.2 Response assertion

image.png
Apply to

  • main sample only: This assertion is for the main request
  • main sample and sub-sample:该断言针对主、次请求,例如重定向的场景,可能会使用到该选项

测试字段:选择需要对哪个数据做判断

  • 忽略状态:忽略jmeter默认的状态判断,来跑响应断言中对于状态的断言

响应断言模式匹配规则

  • 包括(Contains):如果响应中包含了指定的字符串,判断为成功,支持正则表达式
  • 匹配(Matches):如果响应完全匹配指定的字符串,判断为成功,支持正则表达式
  • 相等(Equals):如果响应完全匹配指定的字符串,判断为成功,不支持正则表达式
  • 字符串(Substring):如果响应中包含了指定的字符串,判断为成功,不支持正则表达式
  • 最常用的是字符串,性能测试只需要判断业务是否跑通,无需写过于复杂的断言

2.2.3 测试计划

定义全局变量,例如域名及端口号
image.png
接口中可通过${变量名称}配置
image.png

2.2.4 参数化

2.2.4.1 通过【函数助手】生成各种函数

功能位置:工具栏倒数第二个
常用的函数例如:

  • 生成随机数:Random函数

image.png
输入完范围后,点击【生成】按钮,复制【当前JMeter变量】的语句,粘贴至【参数】的【值】中
image.png

  • 随机字符串:RandomStringimage.png

image.png
点击【生成】按钮后,${__RandomString(8,abcdefghijklmQ39589fsafdgAAA,)} 函数字符串会自动复制到剪切板

  • 时间戳

两个参数皆为可选填,都不填也可,直接点击生成就可以直接用
image.png
填了参数
image.png

  • uuid

image.png

2.2.4.2 文件参数化

1、**CSVRead:**从文本文件中读取数据
优点:该函数适用于使用登录后,仍然需要用这些账号进行一系列操作的压测
image.png
第一个参数填文件的绝对路径,第二个参数填第几列,例如下图中:第一列是登录接口的用户名,第二列是密码
image.png
注意:接口轮询中使用txt文件中的用户数据数量,取决于线程数的数量
线程数=1时,无论循环次数为几,皆使用文件中的第一条用户数据
image.png
线程数=2时,调了两条txt中的用户数据
image.png
线程数=4时,重复调用了两遍文件中的两条数据
image.png
使用函数生成的参数来替换接口中的参数,如下图中的mobile、password字段
image.png

PS:存储函数的变量名
2、CSV Data Set Config
功能添加路径:线程组→添加→配置元件→CSV Data Set Config
image.png

  • Allow quoted data(是否允许带引号):选择true,读取中文时会导致参数值出现乱码

文件编码:可以不填

  • 如果接口中的参数是用西文逗号隔开的(例如:“user”:“username,password”),那么txt数据就不可以再用逗号隔开,可以用【\t】代替,在txt中为用tab键隔开,也可以用别的符号隔开
    | Recycle on EOF(遇到文件结束符再次循环?) | Stop thread onEOF(遇到文件结束符停止线程?) | 参数效果 |
    | — | — | — |
    | True | False | 重复 |
    | False | True | 唯一 |

  • 参数效果=唯一 举例:txt有四条数据,线程数=2,循环次数=3,此时接口只会跑四次,取的txt中四条数据,第五条因需重头取,导致数据重复,所以不会继续运行

  • 参数替换方式

image.png

注意:使用CSV Data Set Config读取数据,无论线程数与循环次数是几,每次查询都是查询下一条数据,若所有数据都读取了一遍,则会从头读取第二遍
线程数=1,循环次数=2时,会使用文件中的两条用户数据
image.pngimage.png

假设txt中是四条用户数据,线程数=2,循环次数=2,在轮询时,会依次读取文件中的四条用户数据
image.png

2.2.5 线程组

线程数:假设有多少用户正在同时使用
多用户场景时,无需参考查看结果树中的接口顺序,其实是同时发生的

2.2.6 数据关联

2.2.6.1 方法一:后置处理器———JSON提取器

image.png
image.png
apply to:一般选main sample only (主请求)
Name of created values:对提取的变量起名
JSON Path expression:要提取的变量(用jsonpath写)

  • 切记,如遇到数据在json中的数组下,记得指定取数组中的第几个,不然会取不出来数据
  • 1、提取最深层某字段的其中一个数据:$.docGroups[0].documents[0].docId
{
    
    
    "responseStatus": {
    
    
    },
    "docGroups": [
        {
    
    
            "documents": [
                {
    
    
                    "docId": 38604724,
                    "startTime": 1673406999
                },
             		{
    
    
                    "docId": 2,
                    "startTime": 1673406998
                }
    ],
    "events": []
}
  • 2、提取某字段在该响应中的所有数据$.docGroups[0].documents[*].docId
{
    
    
    "responseStatus": {
    
    
    },
    "docGroups": [
        {
    
    
            "documents": [
                {
    
    
                    "docId": 1,
                    "startTime": 1673406999
                },
             		{
    
    
                    "docId": 2,
                    "startTime": 1673406998
                }
    ],
    "events": []
}

Match No:想提取第几个数据

  • Match No = 0,则会随即返回其中一个数据
  • 填几,则会返回几个
  • Match No =-1,返回所有的数据

若其他接口想调用取到的值,如下图catalogId字段一样使用即可
image.png

2.2.6.2 调试取样器

image.png
调试取样器可以打印出来Jmeter运行过程中保存下来的参数,需要配合查看结果树使用,无需配置任何数据
image.png
结果树中可看到获取到的get_docID值
image.png

2.2.6.3 方法二:后置处理器——正则表达式提取器

可以通过正则表达式来获取http请求返回的数据
image.png
引用名称:匹配后的结果,保存到一个参数中,如param
正则表达式
三步走:
1、拷贝目标数据和左右边界
2、把目标数据用括号括起来
3、把目标数据用.+?代替
模板 1 1 1表示取匹配到的第一组数据, 2 2 2为第二组
匹配数字:当某组数据中包含多少个参数时,0代表随机,1代表该组的第一个参数,2表示第二 个。。。-1代表获取全部的参数,这个时候,引用名称就变成了参数数组,可以通过param_n来 获取指定的参数,当有多组数据时,第一组为param_1_g1,第二组为param_1_g2
结果:看倒数第四行的re_docid字段,是通过正则提取器提取到的第一个文章id
image.png

2.2.7 聚合报告

image.png
模拟用户使用时,循环次数要选【永久】
image.png
聚合报告结果:image.png
#样本: 表示一共发出了多少个请求Average:平均响应时间
中位数:类似于50% Line90% Line: 假设该值为20,那么90%用户的响应时间小于等于20msMin:最小响应时间
Max/最大值: 最大响应时间
Error%/异常%: 错误率,出现错误的请求数量/请求的总数Throughput:吞吐量KB/Sec: 每秒从服务器端接收到的数据量
吞吐量:默认情况下表示每秒完成的请求数(Request per Second) 对于接口测试来说,Jmeter里的吞吐量=TPS
保存结果:聚合报告底部可保存结果数据
image.png

tip:
1、若两接口在同一线程组下,TPS值一致,但响应时间不一定一致
2、有关联关系的接口放在同一个线程组下,无关联的接口们需独立存放在不同的线程组下

2.2.8 定时器

1、Jmeter中的定时器类似于loadrunner中的pacing值和think_time
1)定时器是在
每个sampler(采样器)之前执行的
,而不是之后
2)定时器是有作用域的;当执行一个sampler之前时,所有当前作用域内的定时器都会被执行。且所有的sampler执行前都会执行定时器
3)如果希望定时器仅应用于其中一个sampler,则把该定时器作为子节点加入

2、常用的定时器

  • 固定定时器:设置一个固定的延迟时间,单位ms

image.png

  • 同步定时器(synchronizing timer):在该定时器处,使线程等待,一直到指定的线程个数达到 后,再一起释放。可以在瞬间制造出很大的压力。它和loadrunner的集合点差不多的功能
    • 集合点
      • 集合点是为了增加瞬间并发压力的一种机制,在脚本中增加一个标记,所有虚拟用户执行到标记 处会进行等待,等所有用户都到达后,再同时继续执行下一步操作。
      • 优点:对服务器来说,会产生一种瞬间高并发
      • 缺点:对服务器来说,平均压力会降低
    • 需要加集合点的场景 :
      • 根据业务来选择,如果业务场景是瞬间高并发类型的,如抢购、秒杀等,需要加集合点; 其他的场景都不需要加,一般加了集合点后,就不使用tps来衡量系统性能 集合点功能要慎重选择,因为加了集合点后,系统的平均压力会降低
    • 超时时间=0,则不会发生超时;超时时间>0,等待X毫秒后,已处理完上一步的的线程组数进行并发

image.png

  • 常量控制器:可以控制每分钟tps的总量,限制最高tps (线上测试最好加该控制器,以防压爆线上)

image.png

2.2.9 逻辑控制器

常用的逻辑控制器:
1、循环控制器:可以设置该控制器内的sampler执行的次数,循环次数与线程的循环次数各自独立

  • 主要作用于多个请求时

image.png
image.png
此条件下,【获取专栏详情页的资讯列表】接口仅执行1次,【请求2】接口执行会执行6次

2、if控制器:根据判断条件决定是否执行该控制器内的请求,如果是字符串比较条件,参数和字符串 都需要加引号
条件格式:
KaTeX parse error: Expected group after '_' at position 2: {_̲_jexl3(条件表达式)}<…{__jexl3(KaTeX parse error: Expected 'EOF', got '}' at position 11: {num} > 5)}̲、 <br />2、若相比较的…{__jexl3(“${ip}”) == “xxxxx”)}
image.png
3、仅一次控制器:该控制器内的请求只执行一次,无论线程循环多少次

  • 针对单个线程

image.png
image.png
此种情况下本应【请求2】【请求3】皆执行6次,但因为【请求3】在【仅一次控制器】下,最终结果为:
【请求2】执行6次【请求3】执行1次

4、foreach控制器,可以遍历某个参数数组,循环获取数组中的参数
参数是通过其他接口通过提取器提取出来的参数数组,再把参数循环附入需要这些参数的接口
image.png
结束循环字段:${get_docId_matchNr}取字数组末尾的get_docId_matchNr=12,方便标记,也不会产生写死的情况(只能获取到get_docId_9的情况)
输入变量法前缀:取自于结果树中get_docId(名字是自己在提取器中设置的变量名)
image.png

2.2.10 Http cookie管理器

2.2.10.1 cookie和session

cookie数据保存在客户端,session数据保存在服务器端。cookie有安全隐患,但是Session过多的时候会消耗服务器资源

  • Cookie 机制:正统的 Cookie 分发是通过扩展 HTTP 协议来实现的,服务器通过在 HTTP 的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的 Cookie。然而纯粹的客户端脚本如 JavaScript 或者 VBScript也可以生成 Cookie。而 Cookie 的使用是由浏览器按照一定的原则在后台自动发送给服务器的。浏览器检查所有存储的 Cookie,如果某个 Cookie 所声明的作用范围大于等于将要请求的资源所在的位置,则把该 cookie 附在请求资源的 HTTP 请求头上发送给服务器。
  • Session 机制:Session 机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。

Cookie 存在一定的全安隐患。Cookie 像我们以前用的存折,用户的存钱、取钱都会记录在这张存折上(即浏览器中会保存所有用户信息),那么对于有非分想法的人可能会去修改存折上的数据(这个比喻忽略掉银行同样会记录用户存取款的金额)。相对于存折,银行卡要全安的得多,客户拿到的只是一个银行卡号(即浏览器只保留一个 Sessionid),那么用户的存钱、取钱都会记录在银行的系统里(即服务器端),只得到一个 sessionid 是没有任何意义的,所以相对于 Cookie 来说就会安全很多。
cv文章~~

2.2.10.2 cookie管理器

位置:
image.png
使用:
image.png
1、名称:取自抓包接口中cookie下,对应的cookie名称,具体其中哪个字段作为cookie需问开发image.png
2、值:即对应的cookie值,配置的cookie必须是有效的,无效接口会有对应的提示:比如用户无效啊,用户未登录~之类的
3、域:接口的域名,全局配置的话,可用 i p 对应的名称 写,配置如下图中,可写为 {ip对应的名称}写,配置如下图中,可写为 ip对应的名称写,配置如下图中,可写为{ip}image.png

无需每次通过抓包获取cookie的便捷方法
image.png
调用login接口获取cookie,http cookie管理器无需填写内容、接口中无需调用,管理器会自动获取接口中cookie塞到需要cookie的接口中

2.2.11 token接口处理

简单了解一下token的使用~

  • 前端登陆的时候向服务器发送请求,服务器验证成功,会生成一个token
  • 前端会存储这个token,放在session或cookie中,用于之后的业务请求身份验证
  • 拿着这个token,可以在当前登录的账号下进行请求业务,发送请求时,token会放在请求头里,服务器收到这个业务请求,验证token,成功就允许这个请求获取数据
  • token可以设置失效期

token知识~
从登录接口中提取token,若是在请求头里需要增加该参数,则在HTTP信息头管理器中添加对应的key、value
image.pngimage.png

2.2.12 上传、下载文件(可以忽略该小节)

内容不全也无真实实例可展示(手头接口不支持)需要细了解请自行搜索
上传文件小点~
1、文件上传原理:浏览器将本地文件内容通过HTTP发送到服务器,服务器收到数据后重新创建一个文件
2、文件上传的HTTP请求content-type:multipart/form-data,MIME类型为application/octet-stream
3、文件上传一般有表单上传和ajax上传两种方式

实现步骤:
1、需要用到的图片本地地址填在txt文本里
image.png
2、把需要读取的txt文件配置在【CSV数据文件设置】中image.png
3、
image.png

下载:
1、文件下载的原理:服务器将文件内容通过HTTP发送到浏览器,浏览器接受到数据后在本地创建一个文件
2、创建文件是浏览器的自沈从文,测试文件下载不需要在本地创建文件
3、文件下载是一个普通的HTTP GET类型请求

2.2.13 WebService接口脚本编写

1、接口配置为http请求

image.png
2、添加header:Content-Type:text/xml;chartset-
image.png

2.2.14 TCP接口脚本编写

image.png
要发送的文本:可能是xml、也可能是十六进制的一串数据,具体数据格式需要找开发了解

2.2.15 JDBC请求脚本编写

1、添加数据库jar包

  • mysql-connector-java-8.0.29.jar阿里盘地址: https://www.aliyundrive.com/s/cW8XgHNyF98
  • 方式一:拷贝mysql驱动包到jmeter/lib目录下
  • 方式二:测试计划处添加驱动jar包(仅针对该测试计划添加某jar包)
  • image.png

3、配置JDBC Connect Configuration
红框中为需要填写的参数;
Database URL:jdbc:mysql://{ip}:{port}/{dbname}?useUnicode=true&characterEncoding=utf8
JDBC Driver class:选择所需使用的数据库
image.png
4、**JDBC Request **
image.png

  1. Variable Name of Pool declared in JDBC Connection Configuration:该字段填写【JDBC Connection Configuration】中【Variable name of createdpool】字段值
  2. Query Type:语句类型
  • Select statement:查询语句类型(select),只支持一条查询语句,多条查询语句只执行第一条
  • Update statement:更新语句类(insert,update,delete),只支持一条更新语句,多条更新语句只执行第一条
  • Prepared Select statement:支持多条查询(select)语句,查询响应数据只展示第一条SQL的查询结果
  • Prepared Update statement:支持多条更新(insert,update,delete)语句,响应数据展示多条更新提示(做参数化最好选择该类型)
  • Callable Statement:支持多条查询、更新(insert,update,delete,select)语句,响应数据展示展示多条数据更新结果。如果是多条select语句同时查询,建议使用Callable Statement,响应数据可以展示多条查询结果值
  1. Parameter values:填写参数的具体的值,或者参数的名称(代替sql语句中问号的值)。可以利用此字段对SQL语句进行参数化
  2. Parameter types:指Parameter Values参数的数据类型,例如:integer,String,double类型
  3. Parameter values 和Parameter types:必须成对出现,且SQL语句中有多个参数,就必须有多少个parameter values 和Parameter types。
  4. Variable names:自己设置的变量名称,用于存放select操作返回的查询结果。有多个字段返回时,需用逗号隔开
  5. Result variable name:用于存放select操作返回的查询结果集
  6. Query timeout:查询超时时间
  7. Handle result set:定义如何处理由callable statements 语句返回的结果

若想保存查询出的数据
1、添加【调试取样器】
2、【JDBC Request】中【Variable names】赋值image.png
调试取样器中可查看到保存下来的结果
image.png

2.3 插件便捷管理

http://jmeter-plugins.org/downloads/all
1、下载jmeter-plugins.jar
2、把jar文件放入%Jmeter_Home%\lib\ext,重启jmeter
3、点击工具栏中的图标image.png,可对插件进行管理

可能会用到的插件:

  • 3 Basic Graph: Real-time tps and response time plug-ins available under windows

image.png
image.png
image.png
image.png

  • Custom JMeter Functions
  • Random CSV Data Set Config
  • PerfMon: Server-side performance real-time monitoring plug-in

Installation:
1. Search and check the required plug-in
image.png
2. Click and wait. It will automatically restart after the download is completed.
image.png

Guess you like

Origin blog.csdn.net/TDLDDMZ/article/details/130913897