1疟暖、驅(qū)動(dòng)包選擇
如果MongoDB版本是3.x以下卡儒,那么用jmeter自帶的mongo-java-driver-2.11.3.jar即可;
如果MongoDB版本是3.x以上俐巴,則需要mongo-java-driver-2.13.2.jar骨望,或者更高版本。
將驅(qū)動(dòng)包放在 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); //根據(jù)IP赎线、端口連mongo
DB db = mongoClient.getDB("test"); //選擇數(shù)據(jù)庫
Set<String> collectionNames = db.getCollectionNames();
log.info(db.getName() + "包含如下集合:" + collectionNames.size());
for (String collectionName : collectionNames) {
log.info(collectionName);
}
log.info("數(shù)據(jù)庫連接成功");
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"));
運(yùn)行jmeter廷没,查看效果:
3糊饱、由于直接在jmeter上寫代碼不是太方便,建議在IDEA上調(diào)試java代碼
建maven項(xiàng)目颠黎,添加依賴另锋,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("數(shù)據(jù)庫連接成功");
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());
}
}
}