写这篇文章的原因,是jmeter无法满足我们的业务需求,对此记录下自定义函数开发过程

jmeter非常强大,五脏俱全。但是业务层面的问题仍然无法使用通用方案去解决。比如我们的小程序接口登录必须带有小程序生成的认证信息。如果我们在接口没有传递这个认证信息,我们就一直会拒绝在门外,请求不到真正要的数据。jmeter提供了自定义函数开发的功能,那我们就可以通过使用和小程序一致的算法去生成认证信息,存放到接口中传递给服务器。上面的问题得到了解决。本文将的是jmeter自定义函数开发的一整个过程

环境准备:

1、开发工具:Eclipse IDE for Java Developers
2、JDK8:jdk 1.8
3、JMeter:Jmeter 5.1.1
备注:
Jmeter是我们要的测试工具
jdk环境是jdk+jre,java开发和运行环境
eclipse是我们的ide,用来开发Jmeter自定义函数

安装

步骤一:eclipse安装

这个没什么好说的,全都是next 就行,主要是留意自己的工作空间(workspace)的目录设置

步骤二:新建一个maven项目

Maven:一个优秀的项目管理工具,可以自动处理依赖等逻辑
新建maven项目截图1.png
Image 233.png

选择一个工作空间,即可
选择工作空间.png

这里的分类Catalog加载可能缓慢,可以切换到Internal,筛选器Filter会比较快速的加载出插件列表。
选择mavan-archtype-quickstart
点击下一步
选择maven.png

会自动下载完成并跳转到新建New Maven Project页面
下载完成之后new maven project页面.png

New Maven Project里,Group Id和Artifact Id虽然说可以随意,但是尽量遵循规范:
Group Id(组织):域.公司名称,示例:com.rrzuji,org.apache
Articfact Id(项目):项目名称.functions,示例:test.functions,特别注意,Jmeter的Articfact Id比如以.functions结尾,否则Jmeter不能识别
设置包名等.png

设置maven 镜像源,否则等下配置POM文件后,拉取依赖要几个钟。
依次在菜单栏上打开windows-Proference
在弹出的设置窗口搜索maven,找到并点击 User Settings
看到右边的User Settings,我在本地电脑是没有settings.xml这个文件的。所以在在对应的位置新建一个,比如我这边是C:Userslonelylizard.m2
新建settings.xml后粘贴如下代码进去:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <mirrors>
    <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
</settings>

如果上面这一段不能用,则粘贴下面这一段:

<?xml version="1.0" encoding="UTF-8"?>
 
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
 
<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single
 |                 user, and is normally provided in
 |                 ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all
 |                 Maven users on a machine (assuming they're all using the
 |                 same Maven installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start
 | at getting the most out of your Maven installation. Where appropriate, the
 | default values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
 
 
  <!--<localRepository>C:/Users/Administrator/.m2/repository</localRepository>  -->
  
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set
   | to false, maven will use a sensible default value, perhaps based on some
   | other setting, for the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->
 
  <!-- offline
   | Determines whether maven should attempt to connect to the network when
   | executing a build. This will have an effect on artifact downloads,
   | artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->
 
  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when
   | resolving plugins by their prefix, i.e. when invoking a command line like
   | "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
   | already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>
 
  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to
   | the network. Unless otherwise specified (by system property or command-
   | line switch), the first proxy specification in this list marked as active
   | will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
 
  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used
   | within the system. Authentication profiles can be used whenever maven must
   | make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a
     | particular server, identified by a unique name within the system
     | (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR
     |       privateKey/passphrase, since these pairings are used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
 
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>
 
  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote
   | repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving
   | certain artifacts. However, this repository may have problems with heavy
   | traffic at times, so people have mirrored it to several places.
   |
   | That repository definition will have a unique id, so we can create a
   | mirror reference for that repository, to be used as an alternate download
   | site. The mirror site will be the preferred server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository.
     | The repository that this mirror serves has an ID that matches the
     | mirrorOf element of this mirror. IDs are used for inheritance and direct
     | lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
 
    <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
 
 
 
  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways,
   | and which can modify the build process. Profiles provided in the
   | settings.xml are intended to provide local machine-specific paths and
   | repository locations which allow the build to work in the local
   | environment.
   |
   | For example, if you have an integration testing plugin - like cactus -
   | that needs to know where your Tomcat instance is installed, you can
   | provide a variable here such that the variable is dereferenced during the
   | build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One
   | way - the activeProfiles section of this document (settings.xml) - will be
   | discussed later. Another way essentially relies on the detection of a
   | system property, either matching a particular value for the property, or
   | merely testing its existence. Profiles can also be activated by JDK
   | version prefix, where a value of '1.4' might activate a profile when the
   | build is executed on a JDK version of '1.4.2_07'. Finally, the list of
   | active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to
   |       specifying only artifact repositories, plugin repositories, and
   |       free-form properties to be used as configuration variables for
   |       plugins in the POM.
   |
   |-->
 
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated
     | using one or more of the mechanisms described above. For inheritance
     | purposes, and to activate profiles via <activatedProfiles/> or the
     | command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a
     | consistent naming convention for profiles, such as 'env-dev',
     | 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
     | will make it more intuitive to understand what the set of introduced
     | profiles is attempting to accomplish, particularly when you only have a
     | list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and
     | provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>
      <activation>
        <jdk>1.4</jdk>
      </activation>
      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->
 
    <!--
     | Here is another profile, activated by the system property 'target-env'
     | with a value of 'dev', which provides a specific path to the Tomcat
     | instance. To use this, your plugin configuration might hypothetically
     | look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone
     |       set 'target-env' to anything, you could just leave off the
     |       <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>
      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>
      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>
 
  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

设置镜像源1.png
settings.xml路径.png

在POM文件添加Jmeter依赖:

在 <dependencies>节点中,添加如下代码:
注意,这里的Jmeter<version>最好跟你现在用的jmeter版本一致,已确保写出来的组件是兼容的

<dependency>
          <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_core</artifactId>
        <version>5.1.1</version>
    </dependency>
    <dependency>
          <groupId>org.apache.jmeter</groupId>
        <artifactId>ApacheJMeter_functions</artifactId>
        <version>5.1.1</version>
    </dependency>

整个POM结构如图
POM文件结构.png

POM文件点击一下保存,会自动拉下依赖,整个过程大概十分钟
POM配置后下载进度.png

下载完成后你可以看到项目的Maven Dependencies下多了非常多的jar包
Maven Dependencies.png

OK,整个配置完成了,下面进行jmeter自定义函数开发,新建一个类。必须实现Jmeter的AbstracFunction

实现AbstracFunction.png

配置完默认需要实现四个方法
getArgumentDesc()//展示参数的填写描述
execute(SampleResult previousResult, Sampler currentSampler)//获取到参数后的执行方法,return的值会返回给Jmeter
setParameters(Collection<CompoundVariable> parameters)//获取参数
getReferenceKey()//展示自定义函数的名称
下面是一个示例


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

public class Test extends AbstractFunction {
    private static final List<String> desc = new LinkedList<String>();
    private static final String KEY = "_测试啊";
    private Object[] values;
    static {
        desc.add("请输入 用户id");
        desc.add("这里是预留参数,将来可能会用到,你现在输了也没用");
    }
    public List<String> getArgumentDesc() {
        // TODO Auto-generated method stub
        //该函数用来获取对输入参数的描述
        return desc;
    }

    @Override
    public String execute(SampleResult arg0, Sampler arg1) throws InvalidVariableException {
        //获取用户输入第一个参数的值
        String userid = ((CompoundVariable) values[0]).execute();
        return userid;
    }

    @Override
    public String getReferenceKey() {
        // TODO Auto-generated method stub
        //jmeter自定义函数显示名称获取
        return KEY;
    }

    @Override
    public void setParameters(Collection<CompoundVariable> arg0) throws InvalidVariableException {
        // TODO Auto-generated method stub
        //获取输入的值
        //检查参数
        checkParameterCount(arg0,1,2);
        values = arg0.toArray();
//        System.out.println(values[1]);
    }
}

OK,demo写完了,开始打包成jar

在项目上右键单击,选择run as-> Maven Build
在Goals填入:package
点击Apply,点击Run即可看到下面的console开始输出打包的信息,直到看到Build Success即打包成功
遇到编译失败的,看console报错信息对应查找
打包1.png
打包2.png
构建成功.png

刚才控制台有提示已导出到某个位置留意到了吗?一般在项目的target目录下,比如我是:

D:eclipse-wordspacemini.functionstargetmini.functions-0.0.1-SNAPSHOT.jar

复制到你的Jmeter安装目录lib->ext下面

复制到Jmeter目录.png

开始测试环节了

打开Jmeter,ctrl+shift+F1打开函数助手,找到你的函数
找到函数助手.png

输入第一个参数的值,点击生成,result的值和预期的一样
测试函数.png

至此Jmeter自定义函数已调试通过,可在Jmeter去调用:
调用格式:${_测试啊(自定义参数,)}
比如我在一个线程组中导入csv文件,并设置导入的变量为${username},
那么我能在其他需要的地方传入给自定义函数,并计算出结果返回来:${_测试啊(${username},)}