1、驱动包选择
如果MongoDB版本是3.x以下,那么用jmeter自带的mongo-java-driver-2.11.3.jar即可;
如果MongoDB版本是3.x以上,则需要mongo-java-driver-2.13.2.jar,或者更高版本。
将驱动包放在 apache-jmeter-x.x\lib目录下或者apache-jmeter-x.x\lib\ext目录下即可
2、添加Sampler,编写java代码访问mongo
可选择添加JSR223 Sampler(groovy)或者BeanShell Sampler,这2种采样器均支持java,但略有不同,语法有些许差异。此处以JSR223 Sampler(groovy)为例。
代码如下:
import com.mongodb.*;
import java.util.Set;
MongoClient mongoClient = new MongoClient("127.0.0.1",27017); //根据IP、端口连mongo
DB db = mongoClient.getDB("test"); //选择数据库
Set<String> collectionNames = db.getCollectionNames();
log.info(db.getName() + "包含如下集合:" + collectionNames.size());
for (String collectionName : collectionNames) {
log.info(collectionName);
}
log.info("数据库连接成功");
DBCollection dbCollection = db.getCollection("col_1"); //选择集合
log.info("集合连接成功");
BasicDBObject searchObj = new BasicDBObject();
searchObj.put("name", "zhf");
DBObject result = dbCollection.findOne(searchObj);
log.info("==============================>>>");
log.info(result.toString());
vars.put("email",result.get("email"));
log.info(vars.get("email"));
运行jmeter,查看效果:
3、由于直接在jmeter上写代码不是太方便,建议在IDEA上调试java代码
建maven项目,添加依赖,pom.xml文件参考如下:
<?xml version="1.0" encoding="UTF-8"?>
<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>zhf</groupId>
<artifactId>zhf</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.2</version>
</dependency>
</dependencies>
</project>
测试代码如下:
import com.mongodb.*;
import java.util.Set;
public class Test {
public static void main(String[] args){
try {
MongoClient mongoClient = new MongoClient("127.0.0.1",27017);
DB db = mongoClient.getDB("test");
Set<String> collectionNames = db.getCollectionNames();
System.out.println(db.getName() + "包含如下集合:");
for (String collectionName : collectionNames) {
System.out.println(collectionName);
}
System.out.println("数据库连接成功");
DBCollection dbCollection = db.getCollection("col_1");
System.out.println("集合连接成功");
BasicDBObject searchObj = new BasicDBObject();
searchObj.put("name", "zhf");
DBObject result = dbCollection.findOne(searchObj);
System.out.println(result);
System.out.println(result.get("sex"));
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
网友评论