知识点:
java测试程序运行时间,主要通过两个System.currentTimeMillis()之差获得:
// 设置时间点time1
long time1 = System.currentTimeMillis();
/* 此处为测试的程序代码 */
// 设置时间点time2
long time2 = System.currentTimeMillis();
// 计算运行时间值
long period = time2 - time1;
返回单位为毫秒mm的long型时间差
测试代码:
MongoDB db = new MongoDB();
long time1 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
BsonDocument user = db.findOne(eq("Status",1),"User");
System.out.println(user);
System.out.println("one-"+i);
}
long time2 = System.currentTimeMillis();
long period = time2 - time1;
System.out.println("period="+(period/1000));
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
time1 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("XXXX").withCodecRegistry(pojoCodecRegistry);
MongoCollection<User> cUser = database.getCollection("User", User.class);
User doc1 = cUser.find(eq("Status", 1)).first();
//System.out.println(doc1);
}
System.out.println("two-"+i);
}
time2 = System.currentTimeMillis();
period = time2 - time1;
System.out.println("period="+(period/1000));
运行结果:
使用mongotemplate访问mongo,运行10万次,花费时间213秒(连接变量用static)。
每次都new一个连接的情况,查询10万次,花费时间719秒,并且过程中很容易遇到连接被关闭的情况,mongodb的连接自带连接池功能