MongoClient连接数据库
public class DbManager { private static volatile DbManager instance; private static final Logger logger = LoggerFactory.getLogger(DbManager.class); private MongoClient mongoClient; private DbManager() { } public static DbManager getInstance() { if (null == instance) { synchronized (DbManager.class) { if (null == instance) { instance = new DbManager(); instance.init(); } } } return instance; } private void init() { // 连接池选项 // 选项构建者 com.mongodb.MongoClientOptions.Builder builder = new MongoClientOptions.Builder(); // 每个地址最大请求数 builder.connectionsPerHost(8); builder.threadsAllowedToBlockForConnectionMultiplier(4); // 设置连接超时时间 builder.connectTimeout(10000); // 设置最大等待时间 builder.maxWaitTime(120000); // 读取数据的超时时间 builder.socketTimeout(1500); MongoClientOptions options = builder.build(); List<ServerAddress> hosts = new ArrayList<ServerAddress>(); String host = "127.0.0.1";
logger.info("dbhost:"+host); int port = 27017; ServerAddress serverAddress = new ServerAddress(host, port); hosts.add(serverAddress); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); MongoCredential credential = MongoCredential.createCredential("admin","admin","123456".toCharArray()); // 需要验证 credentials.add(credential);
//不使用用户名密码 // mongoClient = new MongoClient(hosts);
//使用用户名密码 mongoClient=new MongoClient(serverAddress, Arrays.asList(credential)); } public MongoClient getMongoClient() { return mongoClient; } public DB getDataDb() { DB db = mongoClient.getDB("data"); return db; } }
我不是来改变世界的