Gatling 入门

1.新建一个测试接口项目

里面代码非常简单,就一个hi接口:

package com.example.gatlingdemo.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;@RestController
public class HelloController {private static AtomicInteger atomicInteger=new AtomicInteger(0);@GetMapping("/hi")public String hi(){System.out.println(atomicInteger.getAndIncrement());return LocalDateTime.now().toString();}}

建议大家直接使用SpringBoot完成这个API,

2.新建一个Gatling测试项目

使用的jdk是1.8

1.新建Maven项目,添加依赖,最新的gatlin依赖是3.9.5, 整个pom.xml是:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>io.gatling.demo</groupId><artifactId>gatling-maven-plugin-demo-java</artifactId><version>3.9.5</version><properties><!-- use the following if you're compiling with JDK 8--><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><!-- comment the 2 lines above and uncomment the line bellow if you're compiling with JDK 11 or 17 --><!--    <maven.compiler.release>11</maven.compiler.release>--><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><gatling.version>${project.version}</gatling.version><gatling-maven-plugin.version>4.3.4</gatling-maven-plugin.version><maven-compiler-plugin.version>3.10.1</maven-compiler-plugin.version><maven-jar-plugin.version>3.2.2</maven-jar-plugin.version></properties><dependencies><dependency><groupId>io.gatling.highcharts</groupId><artifactId>gatling-charts-highcharts</artifactId><version>${gatling.version}</version><scope>test</scope></dependency></dependencies><build><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>${maven-compiler-plugin.version}</version></plugin><plugin><artifactId>maven-jar-plugin</artifactId><version>${maven-jar-plugin.version}</version></plugin><plugin><groupId>io.gatling</groupId><artifactId>gatling-maven-plugin</artifactId><version>${gatling-maven-plugin.version}</version><configuration><!-- Enterprise Cloud (https://cloud.gatling.io/) configuration reference: https://gatling.io/docs/gatling/reference/current/extensions/maven_plugin/#working-with-gatling-enterprise-cloud --><!-- Enterprise Self-Hosted configuration reference: https://gatling.io/docs/gatling/reference/current/extensions/maven_plugin/#working-with-gatling-enterprise-self-hosted --></configuration></plugin></plugins></build>
</project>

在resource下新建配置gatling.conf文件:

#########################
# Gatling Configuration #
########################## This file contains all the settings configurable for Gatling with their default valuesgatling {core {#outputDirectoryBaseName = "" # The prefix for each simulation result folder (then suffixed by the report generation timestamp)#runDescription = ""          # The description for this simulation run, displayed in each report#encoding = "utf-8"           # Encoding to use throughout Gatling for file and string manipulation#simulationClass = ""         # The FQCN of the simulation to run (when used in conjunction with noReports, the simulation for which assertions will be validated)#elFileBodiesCacheMaxCapacity = 200      # Cache size for request body EL templates, set to 0 to disable#rawFileBodiesCacheMaxCapacity = 200     # Cache size for request body Raw templates, set to 0 to disable#rawFileBodiesInMemoryMaxSize = 1000     # Below this limit, raw file bodies will be cached in memory#pebbleFileBodiesCacheMaxCapacity = 200  # Cache size for request body Peeble templates, set to 0 to disable#feederAdaptiveLoadModeThreshold = 100   # File size threshold (in MB). Below load eagerly in memory, above use batch mode with default buffer size#shutdownTimeout = 10000                 # Milliseconds to wait for the actor system to shutdownextract {regex {#cacheMaxCapacity = 200 # Cache size for the compiled regexes, set to 0 to disable caching}xpath {#cacheMaxCapacity = 200 # Cache size for the compiled XPath queries,  set to 0 to disable caching}jsonPath {#cacheMaxCapacity = 200 # Cache size for the compiled jsonPath queries, set to 0 to disable caching}css {#cacheMaxCapacity = 200 # Cache size for the compiled CSS selectors queries,  set to 0 to disable caching}}directory {#simulations = user-files/simulations # Directory where simulation classes are located (for bundle packaging only)#resources = user-files/resources     # Directory where resources, such as feeder files and request bodies are located (for bundle packaging only)#reportsOnly = ""                     # If set, name of report folder to look for in order to generate its report#binaries = ""                        # If set, name of the folder where compiles classes are located: Defaults to GATLING_HOME/target.#results = results                    # Name of the folder where all reports folder are located}}socket {#connectTimeout = 10000                 # Timeout in millis for establishing a TCP socket#tcpNoDelay = true#soKeepAlive = false                    # if TCP keepalive configured at OS level should be used#soReuseAddress = false}netty {#useNativeTransport = true              # if Netty native transport should be used instead of Java NIO#allocator = "pooled"                   # switch to unpooled for unpooled ByteBufAllocator#maxThreadLocalCharBufferSize = 200000  # Netty's default is 16k}ssl {#useOpenSsl = true                    # if OpenSSL should be used instead of JSSE (only the latter can be debugged with -Djava.net.debug=ssl)#useOpenSslFinalizers = false         # if OpenSSL contexts should be freed with Finalizer or if using RefCounted is fine#handshakeTimeout = 10000             # TLS handshake timeout in millis#useInsecureTrustManager = true       # Use an insecure TrustManager that trusts all server certificates#enabledProtocols = []             # Array of enabled protocols for HTTPS, if empty use Netty's defaults#enabledCipherSuites = []          # Array of enabled cipher suites for HTTPS, if empty enable all available ciphers#sessionCacheSize = 0              # SSLSession cache size, set to 0 to use JDK's default#sessionTimeout = 0                # SSLSession timeout in seconds, set to 0 to use JDK's default (24h)#enableSni = true                     # When set to true, enable Server Name indication (SNI)keyStore {#type = ""      # Type of SSLContext's KeyManagers store#file = ""      # Location of SSLContext's KeyManagers store#password = ""  # Password for SSLContext's KeyManagers store#algorithm = "" # Algorithm used SSLContext's KeyManagers store}trustStore {#type = ""      # Type of SSLContext's TrustManagers store#file = ""      # Location of SSLContext's TrustManagers store#password = ""  # Password for SSLContext's TrustManagers store#algorithm = "" # Algorithm used by SSLContext's TrustManagers store}}charting {#noReports = false       # When set to true, don't generate HTML reports#maxPlotPerSeries = 1000 # Number of points per graph in Gatling reports#useGroupDurationMetric = false  # Switch group timings from cumulated response time to group duration.indicators {#lowerBound = 800      # Lower bound for the requests' response time to track in the reports and the console summary#higherBound = 1200    # Higher bound for the requests' response time to track in the reports and the console summary#percentile1 = 50      # Value for the 1st percentile to track in the reports, the console summary and Graphite#percentile2 = 75      # Value for the 2nd percentile to track in the reports, the console summary and Graphite#percentile3 = 95      # Value for the 3rd percentile to track in the reports, the console summary and Graphite#percentile4 = 99      # Value for the 4th percentile to track in the reports, the console summary and Graphite}}http {#fetchedCssCacheMaxCapacity = 200          # Cache size for CSS parsed content, set to 0 to disable#fetchedHtmlCacheMaxCapacity = 200         # Cache size for HTML parsed content, set to 0 to disable#perUserCacheMaxCapacity = 200             # Per virtual user cache size, set to 0 to disable#warmUpUrl = "https://gatling.io"          # The URL to use to warm-up the HTTP stack (blank means disabled)#enableGA = true                           # Very light Google Analytics (Gatling and Java version), please support#pooledConnectionIdleTimeout = 60000       # Timeout in millis for a connection to stay idle in the pool#requestTimeout = 60000                    # Timeout in millis for performing an HTTP request#enableHostnameVerification = false        # When set to true, enable hostname verification: SSLEngine.setHttpsEndpointIdentificationAlgorithm("HTTPS")dns {#queryTimeout = 5000                     # Timeout in millis of each DNS query in millis#maxQueriesPerResolve = 6                # Maximum allowed number of DNS queries for a given name resolution}}jms {#replyTimeoutScanPeriod = 1000  # scan period for timedout reply messages}data {#writers = [console, file]      # The list of DataWriters to which Gatling write simulation data (currently supported : console, file, graphite)console {#light = false                # When set to true, displays a light version without detailed request stats#writePeriod = 5              # Write interval, in seconds}file {#bufferSize = 8192            # FileDataWriter's internal data buffer size, in bytes}leak {#noActivityTimeout = 30  # Period, in seconds, for which Gatling may have no activity before considering a leak may be happening}graphite {#light = false              # only send the all* stats#host = "localhost"         # The host where the Carbon server is located#port = 2003                # The port to which the Carbon server listens to (2003 is default for plaintext, 2004 is default for pickle)#protocol = "tcp"           # The protocol used to send data to Carbon (currently supported : "tcp", "udp")#rootPathPrefix = "gatling" # The common prefix of all metrics sent to Graphite#bufferSize = 8192          # Internal data buffer size, in bytes#writePeriod = 1            # Write period, in seconds}}
}

配置日志文件logback-test.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx</pattern></encoder><immediateFlush>false</immediateFlush></appender><!-- uncomment and set to DEBUG to log all failing HTTP requests --><!-- uncomment and set to TRACE to log all HTTP requests --><!--<logger name="io.gatling.http.engine.response" level="TRACE" />--><root level="WARN"><appender-ref ref="CONSOLE" /></root></configuration>

新建IDEAPathHelper类:

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.util.Objects.requireNonNull;public class IDEPathHelper {static final Path mavenSourcesDirectory;static final Path mavenResourcesDirectory;static final Path mavenBinariesDirectory;static final Path resultsDirectory;static final Path recorderConfigFile;static {try {Path projectRootDir = Paths.get(requireNonNull(IDEPathHelper.class.getResource("gatling.conf"), "Couldn't locate gatling.conf").toURI()).getParent().getParent().getParent();Path mavenTargetDirectory = projectRootDir.resolve("target");Path mavenSrcTestDirectory = projectRootDir.resolve("src").resolve("test");mavenSourcesDirectory = mavenSrcTestDirectory.resolve("java");mavenResourcesDirectory = mavenSrcTestDirectory.resolve("resources");mavenBinariesDirectory = mavenTargetDirectory.resolve("test-classes");resultsDirectory = mavenTargetDirectory.resolve("gatling");recorderConfigFile = mavenResourcesDirectory.resolve("recorder.conf");} catch (URISyntaxException e) {throw new ExceptionInInitializerError(e);}}
}

新建类Recorder:

import io.gatling.recorder.GatlingRecorder;
import io.gatling.recorder.config.RecorderPropertiesBuilder;
import scala.Option;public class Recorder {public static void main(String[] args) {RecorderPropertiesBuilder props = new RecorderPropertiesBuilder().simulationsFolder(IDEPathHelper.mavenSourcesDirectory.toString()).resourcesFolder(IDEPathHelper.mavenResourcesDirectory.toString()).simulationPackage("computerdatabase").simulationFormatJava();GatlingRecorder.fromMap(props.build(), Option.apply(IDEPathHelper.recorderConfigFile));}
}

新建包computerdatabase,新建类ComputerDatabaseSimulation:

package computerdatabase;import io.gatling.javaapi.core.ChainBuilder;
import static io.gatling.javaapi.core.CoreDsl.exec;
import static io.gatling.javaapi.core.CoreDsl.rampUsers;
import static io.gatling.javaapi.core.CoreDsl.repeat;
import static io.gatling.javaapi.core.CoreDsl.scenario;
import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.core.Simulation;
import static io.gatling.javaapi.http.HttpDsl.http;
import static io.gatling.javaapi.http.HttpDsl.status;
import io.gatling.javaapi.http.HttpProtocolBuilder;public class ComputerDatabaseSimulation extends Simulation {ChainBuilder myApp =// Note how we force the counter name, so we can reuse itrepeat(4, "i").on(exec(http("test Hi").get("/hi").check(status().is(200))).pause(1));HttpProtocolBuilder httpProtocol =http.baseUrl("http://127.0.0.1:8080").header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9").userAgentHeader("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36").inferHtmlResources().acceptEncodingHeader("gzip, deflate, br");ScenarioBuilder keTest = scenario("test Hi").exec(myApp);{setUp(keTest.injectOpen(rampUsers(2).during(10))).protocols(httpProtocol);}
}

注意:

1.http中的名字必须和scenario 名字一致。

  2.http.baseUrl("http://127.0.0.1:8080") 必须加上前缀http或者https。

构建完成后使用命令:mvn gatling:test 进行测试。

看到下面就是运行成功了

可以查看结果了。

这是最基本的入门了,建议大家查看官方文档:

Gatling - Quickstart

本文的Maven例子来自官网:https://github.com/gatling/gatling-maven-plugin-demo-java

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/114565.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

拼多多开放平台的API接口可以获取拼多多电商数据。以下是API接口流程

使用拼多多开放平台的API接口可以获取拼多多电商数据。以下是一般的API接口流程&#xff1a; 1. 注册开发者账号&#xff1a;首先&#xff0c;您需要在拼多多开放平台注册一个开发者账号。通过开发者账号&#xff0c;您可以获得API密钥和其他必要的信息。 2. 鉴权与认证&…

33、Flink之hive介绍与简单示例

Flink 系列文章 1、Flink 部署、概念介绍、source、transformation、sink使用示例、四大基石介绍和示例等系列综合文章链接 13、Flink 的table api与sql的基本概念、通用api介绍及入门示例 14、Flink 的table api与sql之数据类型: 内置数据类型以及它们的属性 15、Flink 的ta…

给oracle逻辑导出clob大字段、大数据量表提提速

文章目录 前言一、大表数据附&#xff1a;查询大表 二、解题思路1.导出排除大表的数据2.rowid切片导出大表数据Linux代码如下&#xff08;示例&#xff09;&#xff1a;Windows代码如下&#xff08;示例&#xff09;&#xff1a;手工执行代码如下&#xff08;示例&#xff09;&…

vite 配置自动补全文件的后缀名

vite 不建议自动补全&#xff0c;文件的后缀名的 const Home ()>import("/views/Home.vue");文件是必须要加上 .vue 的后缀名的 如果 想要像 webpack 一样的不用写&#xff0c; 可以在vite.config.js中配置如下就可以了

【iOS】Masonry的基本使用

文章目录 前言一、使用Masonry的原因二、约束的常识三、Masonry的简单使用四、Masonry的用例总结 前言 暑假安装了cocoapods&#xff0c;简单使用其调用了SVGKit&#xff0c;但是没有学习Masonry&#xff0c;特此总结博客记录Masonry的学习 一、使用Masonry的原因 Masonry是一…

持续集成与持续交付(CI/CD):探讨在云计算中实现快速软件交付的最佳实践

文章目录 持续集成&#xff08;CI&#xff09;的最佳实践持续交付&#xff08;CD&#xff09;的最佳实践云计算环境下的特别注意事项 &#x1f388;个人主页&#xff1a;程序员 小侯 &#x1f390;CSDN新晋作者 &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏 ✨收录专栏&am…

docker启动paddlespeech服务,并使用接口调用

一、检查docker容器是否启动 1.输入命令 systemctl status docker 启动 systemctl start docker 守护进程重启 sudo systemctl daemon-reload 重启docker服务 systemctl restart docker 重启docker服务 sudo service docker restart 关闭docker service docker…

Django实现音乐网站 ⒂

使用Python Django框架制作一个音乐网站&#xff0c; 本篇主要是歌手详情页-基本信息、单曲列表功能开发实现内容。 目录 歌手基本信息 增加路由 显示视图 模板显示 推荐歌手跳转详情 歌手增加基本信息 表模型增加字段 数据表更新 基本信息增加内容渲染 歌手单曲列表…

TL6478(TI TMS320C6748 DPS)EVM开发板技术讲座 第二讲:USB转串口驱动安装

在开展我们的TL 6748 DSP开发版开发之前,需要先安装usb转串口驱动,才能使得我们的电脑上查询到该设备,使用该设备。底板上存在UART1、UART2,将评估板的 UART2 RS232 调试串口通过 RS232 交叉串口母母线、USB 转 RS232 公头串口线连接至 PC 机的 USB 接口。1. 驱动下载 USB…

TCP协议基础

一&#xff1a; TCP协议是什么&#xff1f; TCP协议是基于面向连接&#xff0c;可靠传输&#xff0c;基于字节流的传输层通信协议 1. 面向连接 TCP协议是一种面向连接的协议&#xff0c;意味着在双方在建立数据传输之前&#xff0c;需要进行一个逻辑上的连接&#xff0c;且是…

分布式搜索引擎

1 DSL查询文档 elasticsearch的查询依然是基于JSON风格的DSL来实现的。 1.1.DSL查询分类 Elasticsearch提供了基于JSON的DSL&#xff08;Domain Specific Language&#xff09;来定义查询。常见的查询类型包括&#xff1a; 查询所有&#xff1a;查询出所有数据&#xff0c;一…

【ES6】—类与继承

一、 定义类 class People {constructor (name, age) {this.name namethis.age age}showName () {console.log(this.name)} } let p1 new People(xiaoxiao, 30) console.log(p1) // People {name: xiaoxiao, age: 30}小节&#xff1a; 使用class关键字声明类使用construc…

瓜分双十一10亿红包设计:在线分享教程?

在如今激烈的市场竞争中&#xff0c;瓜分红包营销活动成为了各大企业争相使用的一种营销手段。这种活动不仅能够吸引用户的关注和参与&#xff0c;还能够提高用户的粘性和忠诚度。那么&#xff0c;如何自建瓜分红包营销活动呢&#xff1f;下面将为大家详细解析。 首先&#xff…

Mysql高阶语句 (一)

一、常用查询 &#xff08;增、删、改、查&#xff09; 对 MySQL 数据库的查询&#xff0c;除了基本的查询外&#xff0c;有时候需要对查询的结果集进行处理。 例如只取 10 条数据、对查询结果进行排序或分组等等 1、按关键字排序 PS:类比于windows 任务管理器 使用 SELECT 语句…

Ansible自动化运维工具

Ansible自动化运维工具 一、Ansible介绍1.Ansible工具&#xff1a;2.Ansible特点及优势3.Ansible核心程序4.Ansible的工作原理及流程 二、部署ansible自动化1.管理端安装ansible2.ansible 目录结构3.配置主机清单4.配置密钥对验证 三、ansible 命令行模块1.command 模块2.shell…

java八股文面试[多线程]——AQS 详细介绍

线程同步除了Synchronized Volatile ReentranLock 之外&#xff0c;还有其他一些用来进行同步的机制。 AQS 简单介绍 AQS 的全称为&#xff08;AbstractQueuedSynchronizer&#xff09;&#xff0c;这个类在 java.util.concurrent.locks 包下面。 AQS 是一个用来构建锁和同步器…

开启智能时代:深度解析智能文档分析技术的前沿与应用

开启智能时代&#xff1a;深度解析智能文档分析技术的前沿与应用 本章主要介绍文档分析技术的理论知识&#xff0c;包括背景介绍、算法分类和对应思路。通过本文学习&#xff0c;你可以掌握&#xff1a;1. 版面分析的分类和典型思想 2. 表格识别的分类和典型思想 3. 信息提取的…

SpringMVC概述与简单使用

1.SpringMVC简介 SpringMVC也叫做Spring web mvc,是 Spring 框架的一部分&#xff0c;是在 Spring3.0 后发布的。 2.SpringMVC优点 1.基于 MVC 架构 基于 MVC 架构&#xff0c;功能分工明确。解耦合&#xff0c; 2.容易理解&#xff0c;上手快&#xff1b;使用简单。 就可以…

1.9 动态解密ShellCode反弹

动态解密执行技术可以对抗杀软的磁盘特征查杀。其原理是将程序代码段中的代码进行加密&#xff0c;然后将加密后的代码回写到原始位置。当程序运行时&#xff0c;将动态解密加密代码&#xff0c;并将解密后的代码回写到原始位置&#xff0c;从而实现内存加载。这种技术可以有效…

WMS中Binder案例

WMS中Binder案例 1、FWK层中AIDL形式1.1 服务端实现Stub1.2 客户端获取proxy 2、紧密相关SurfaceFlinger android12-release 1、FWK层中AIDL形式 Android 接口定义语言 (AIDL)、Android 应用层 到 HAL 层 AIDL形式是Android中binder机制的具体实现。按照规范aidl/hidl文件自动生…