Gatling 入门

news2024/9/25 13:16:55

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 values

gatling {
  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 shutdown
    extract {
      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 it
            repeat(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.coloradmin.cn/o/957961.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

北京开发APP的费用明细

开发APP项目时&#xff0c;在功能确定后需要知道有哪些可能的费用&#xff0c;安排项目预算。北京开发APP的费用明细可能会包括以下几个部分&#xff0c;每个部分都会产生一些费用。今天和大家分享APP费用明细有哪些&#xff0c;希望对大家有所帮助。北京木奇移动技术有限公司&…

地理测绘基础知识(4) 照射计算

照射计算&#xff0c;是一种常用的三维几何计算。已知一个光源的光强图&#xff0c;计算光源投射到地表各处的功率密度。这种计算需求可以直观的理解为计算已知位置、指向、聚光特性的手电筒&#xff0c;计算地表某地点强度。 本文的推导涉及很多旋转&#xff0c;很容易出错和…

ElasticSearch安装为Win11服务

在windows的环境下操作是Elasticsearch,并且喜欢使用命令行 &#xff0c;启动时通过cmd直接在elasticsearch的bin目录下执行elasticsearch ,这样直接启动的话集群名称会默elasticsearch&#xff0c;节点名称会随机生成。 停止就直接在cmd界面按CtrlC 其实我们也可以将elasticse…

Ansible学习笔记14

实现多台的分离实现&#xff1a; [rootlocalhost playbook]# cat example3.yaml --- - hosts: 192.168.17.105remote_user: roottasks:- name: create test1 directoryfile: path/test1/ statedirectory- hosts: 192.168.17.106remote_user: roottasks:- name: create test2 d…

Python—匹配字段

1. 「概述」 在日常开发中&#xff0c;经常需要对数据中的某些字段进行匹配&#xff0c;但这些字段可能存在微小的差异。例如&#xff0c;同一个招聘岗位的数据中&#xff0c;省份字段可能有“广西”、“广西壮族自治区”和“广西省”等不同的写法。为了处理这些情况&#xff…

二叉树的介绍

写在前面&#xff1a; 二叉树是数据结构课程中非常重要的内容&#xff0c;我们针对二叉树的概念、性质以及类型展开详细介绍。 一、概念 二叉树&#xff08;Binary Tree&#xff09;是n&#xff08;n>0&#xff09;个结点的有限集合&#xff0c;该集合或者空集&#xff0…

C语言用递归函数求解斐波那契数

int Fib(int n) {if (n 1 || n 2){return 1;}return Fib(n - 1) Fib(n - 2); }int main() {int i 0;printf("请输入需要第几个斐波那契数\n");scanf("%d", &i);int r Fib(i);printf("%d\n", r);return 0; }

JVM 对象的内存布局

对象头 Mark word 标记字段 用于存储对象自身的运行时数据&#xff0c;如哈希码&#xff08;HashCode&#xff09;、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID、偏向时间戳等 ClassPoint 类型指针 对象指向它的类型元数据的指针&#xff0c;Java虚拟机通过这个指针 来…

C++——shared_ptr:make_shared的用处,与shared_ptr直接构造的区别

shared_ptr shared_ptr继承自__shared_ptr&#xff0c;其中有两个对象&#xff0c;一个是指向资源的指针&#xff0c;一个是控制块&#xff0c;指向一个引用计数对象。控制块中存储了强引用和弱引用的计数&#xff0c;强引用Uses代表shared_ptr对象的引用计数&#xff0c;弱引…

excel怎么设置任意选一个单元格纵横竖横都有颜色

有时excel表格内容过多的时候&#xff0c;我们通过excel设置任意选一个单元格纵横&#xff0c;竖横背景颜色&#xff0c;这样会更加具有辨识度。设置方式截图如下 设置成功后&#xff0c;预览的效果图

常静相伴:深度解析C++中的const与static关键字

个人主页&#xff1a;北海 &#x1f390;CSDN新晋作者 &#x1f389;欢迎 &#x1f44d;点赞✍评论⭐收藏✨收录专栏&#xff1a;C/C&#x1f91d;希望作者的文章能对你有所帮助&#xff0c;有不足的地方请在评论区留言指正&#xff0c;大家一起学习交流&#xff01;&#x1f9…

kafka 命令脚本说明以及在java中使用

一、命令行使用 1.1、topic 命令 1、关于topic,这里用window 来示例 bin\windows\kafka-topics.bat2、创建 first topic,五个分区&#xff0c;1个副本 bin\windows\kafka-topics.bat --bootstrap-server localhost:9092 --create --partitions 5 --replication-factor 1 -…

nacos import com.alibaba.nacos.consistency.entity.ReadRequest

1. 异常情况 import com.alibaba.nacos.consistency.entity.ReadRequest; import com.alibaba.nacos.consistency.entity.Response; import com.alibaba.nacos.consistency.entity.WriteRequest; 2. 解决方法 安装插件&#xff0c;然后重新编译 记住选择Java8

从零做软件开发项目系列之十——项目运维

项目结项后的运维阶段是确保软件持续稳定运行、修复问题、满足用户需求的关键时期。在这个阶段&#xff0c;需要建立有效的维护制度&#xff0c;关注各种问题&#xff0c;并采取相应措施来保障系统的可靠性和可持续性。 1 运维团队 开展服务运维工作&#xff0c;首先需要组建运…

07.Knowing When to Look

目录 前言泛读摘要Introduction小结 精讲方法Encoder-Decoder框架 for Image CaptioningSpatial Attention ModelAdaptive Attention Model Implementation DetailsEncoder-CNNDecoder-RNNTraining details Related Work实验结论 前言 本课程来自深度之眼《多模态》训练营&…

【前端】Vue2 脚手架模块化开发 -快速入门

&#x1f384;欢迎来到边境矢梦的csdn博文&#x1f384; &#x1f384;本文主要梳理Vue2 脚手架模块化开发 &#x1f384; &#x1f308;我是边境矢梦&#xff0c;一个正在为秋招和算法竞赛做准备的学生&#x1f308; &#x1f386;喜欢的朋友可以关注一下&#x1faf0;&#x…

前端项目工程化之代码规范

目录 一、前言二、ESLint三、Prettier四、项目实战4.1 环境依赖版本4.2 使用pnpm4.3 git提交规范 五、资源 收集六、源码地址 一、前言 前端项目工程化之代码规范是指在前端项目中定义一套代码规范&#xff0c;以确保项目中的代码风格和格式一致&#xff0c;提高代码的可读性和…

GaussDB数据库SQL系列-行列转换

一、前言 二、简述 1、行转列概念 2、列转行概念 三、GaussDB数据库的行列转行实验示例 1、行转列示例 1&#xff09;创建实验表&#xff08;行存表&#xff09; 2&#xff09;静态行转列 3&#xff09;行转列&#xff08;结果值&#xff1a;拼接式&#xff09; 4&…

文心一言 VS CHATGPT

由于近几天来&#xff0c;我的手机短信不断收到百度公司对于“文心一言”大模型的体验邀请&#xff08;真是不胜其烦&#xff09;&#xff01;&#xff01;所以我就抱着试试看的态度点开了文心一言的链接&#xff1a;文心一言 目前看来&#xff0c;有以下两点与chatgpt是有比较…

Plex私人影音云盘搭建教程:本地电脑使用内网穿透实现远程访问

文章目录 1.前言2. Plex网站搭建2.1 Plex下载和安装2.2 Plex网页测试2.3 cpolar的安装和注册 3. 本地网页发布3.1 Cpolar云端设置3.2 Cpolar本地设置 4. 公网访问测试5. 结语 1.前言 用手机或者平板电脑看视频&#xff0c;已经算是生活中稀松平常的场景了&#xff0c;特别是各…