java操作mongodb(连接池)(转)
时间:2021-07-01 10:21:17
帮助过:2人阅读
Mongo的实例其实就是一个数据库连接池,这个连接池里默认有10个链接。我们没有必要重新实现这个链接池,但是我们可以更改这个连接池的配置。因为Mongo的实例就是一个连接池,所以,项目中最好只存在一个Mongo的实例。
常见的配置参数:
connectionsPerHost:每个主机的连接数
threadsAllowedToBlockForConnectionMultiplier:线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
maxWaitTime:最大等待连接的线程阻塞时间
connectTimeout:连接超时的毫秒。0是默认和无限
socketTimeout:socket超时。0是默认和无限
autoConnectRetry:这个控制是否在一个连接时,系统会自动重试
还有许多配置,可以参见mongodb的API。
下面看代码:
[java] view plain
copy
print?
- package com.mongo.common;
-
- import java.net.UnknownHostException;
-
- import com.mongodb.DB;
- import com.mongodb.Mongo;
- import com.mongodb.MongoException;
- import com.mongodb.MongoOptions;
-
- public class MongoManager {
- private final static String HOST = "localhost";
- private final static int PORT = 27017;
- private final static int POOLSIZE = 100;
- private final static int BLOCKSIZE = 100;
- private static Mongo mongo = null;
-
- private MongoManager() { }
-
- static {
- initDBPrompties();
- }
-
- public static DB getDB(String dbName) {
- return mongo.getDB(dbName);
- }
-
-
- private static void initDBPrompties() {
-
- try {
- mongo = new MongoClient( HOST, PORT);
- MongoOptions opt = mongo.getMongoOptions();
- opt.connectionsPerHost = POOLSIZE;
- opt.threadsAllowedToBlockForConnectionMultiplier = BLOCKSIZE;
- } catch (UnknownHostException e) {
- } catch (MongoException e) {
-
- }
-
- }
- }
使用的时候,如下所示:
[java] view plain
copy
print?
- public void save(User user) throws UnknownHostException {
- DB myMongo = MongoManager.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
-
- DBObject dbo = (DBObject) JSON.parse(user.toJson());
- userCollection.insert(dbo);
- }
java操作mongodb(连接池)(转)
标签: