使用jmeter连接mongodb进行查询操作

2020-04-03  本文已影响0人  海的那一边

环境:JMeter 5.1.1

步骤:

1.将包mongo-java-driver-3.12.1.jar放到/apache-jmeter-2.13/lib目录下
2.在线程组中添加BeanShell Sampler,编写代码

代码:

1.连接有用户名密码的monogo数据库:
username:数据库用户名
database:数据库名
password:密码
addrs:数据库地址

MongoCredential credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());  
List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
credentials.add(credential);
mongoClient = new MongoClient(addrs,credentials, options); 

2.连接集合

//test为集合名
MongoCollection collection = mongoDatabase.getCollection("test");

3.查询操作:在集合中查询content_uid=${contentUid4}的数据

BasicDBObject query = new BasicDBObject();
query.put("content_uid", "${contentUid4}");
FindIterable oneUser = collection.find(query);
//获取结果中的第一条
Document document = oneUser.first();
String result = document.get("uid");

代码如下:

import com.mongodb.*;
import java.util.Set;
import java.util;
import java.util.List;
import org.bson.Document;
import org.junit.Test;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import org.bson.types.ObjectId;

MongoCredential credential = MongoCredential.createScramSha1Credential("xx", "xx", "xx".toCharArray());
List credentials = new ArrayList();  
credentials.add(credential);
mongoDatabase = new MongoClient(new ServerAddress("192.168.xx.xx", 27017),credentials).getDatabase("ocr");

MongoCollection collection = mongoDatabase.getCollection("test");

BasicDBObject query = new BasicDBObject();
query.put("content_uid", "${contentUid4}");
FindIterable oneUser = collection.find(query);
Document document = oneUser.first();
System.out.println(document);
String result = document.get("uid");
System.out.println(result);
vars.put("pictureUid", result);

参考:
https://www.cnblogs.com/wenbronk/p/6385935.html
https://docs.mongodb.com/ecosystem/drivers/reactive-streams/

上一篇下一篇

猜你喜欢

热点阅读