Gradle與Gatling指令碼整合

黃博文發表於2014-07-23

Gatling作為次時代的效能測試工具,由於其API簡潔明瞭、效能出眾,越來越受歡迎。但是執行Gatling指令碼卻有諸多不便,其提供的預設方式不是很方便。考慮到Gatling指令碼本質上是Scala類,執行的時候還是使用的是java虛擬機器,我們可以將其指令碼的執行與Gradle結合起來。這樣子就可以通過Gradle來執行Gatling指令碼了。

廢話少說,接下來就講述下如何來進行配置。

建立一個標準的maven結構的工程目錄,如下圖所示。

Gradle與Gatling指令碼整合

conf目錄存放Gatling的基本配置檔案。 Gatling的指令碼檔案存放在src/test/scala/simulations包裡面。可以自行在此包下對指令碼檔案再分類。

在build.gradle檔案中引入scala外掛。

1
apply plugin: 'scala'

然後引入有gatling庫的maven repo。

1
2
3
4
5
6
repositories {
    mavenCentral ()
    maven {
        url 'http://repository.excilys.com/content/groups/public'
    }
}

再加入scala和gatling的依賴項。

1
2
3
4
dependencies {
    compile 'org.scala-lang:scala-library:2.10.1'
    testCompile 'io.gatling.highcharts:gatling-charts-highcharts:2.0.0-M3a'
}

把conf資料夾作為test的source檔案。

1
2
3
4
5
6
7
sourceSets {
    test {
        resources {
            srcDir 'conf'
        }
    }
}

建立一個名為gatling的task,目的是執行所有的gatling指令碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
task gatling (dependsOn: 'compileTestScala') << {

    logger.lifecycle (" ---- Executing all Gatling scenarios from: ${sourceSets.test.output.classesDir} ----")

    sourceSets.test.output.classesDir.eachFileRecurse { file ->
        if (file.isFile ()) {

            def gatlingScenarioClass = (file.getPath () - (sourceSets.test.output.classesDir.getPath () + File.separator) - '.class')
                    .replace (File.separator, '.')

            javaexec {
                main = 'io.gatling.app.Gatling'
                classpath = sourceSets.test.output + sourceSets.test.runtimeClasspath
                args '-sbf',
                        sourceSets.test.output.classesDir,
                        '-s',
                        gatlingScenarioClass,
                        '-rf',
                        'build/reports/gatling'
            }
        }

    }

    logger.lifecycle (" ---- Done executing all Gatling scenarios ----")
}

這是藉助於Gatling的command line執行功能來實現的。具體引數指定官網上有,這裡貼出原文。

Command Line Options # Gatling can be started with several options listed below:

  • -nr (–no-reports): Runs simulation but does not generate reports
  • -ro (–reports-only ): Generates the reports for the simulation log file located in /results/
  • -df (–data-folder ): Uses as the folder where feeders are stored
  • -rf (–results-folder ): Uses as the folder where results are stored
  • -bf (–request-bodies-folder ): Uses as the folder where request bodies are stored
  • -sf (–simulations-folder ): Uses as the folder where simulations are stored
  • -sbf (–simulations-binaries-folder ): Uses as the folder where simulation binaries are stored
  • -s (–simulation ): Uses as the name of the simulation to be run
  • -sd (–simulation-description ): Uses as simulation description

我在github上建立了一個示例專案,請參見https://github.com/huangbowen521/gatling-gradle

相關文章