MongoDB3.2 Java连接方式

本文介绍了一个用于初始化MongoDB实例的Java类,通过该类可以创建MongoDB连接,并支持配置选项和认证信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB3.2 数据库连接:

import java.util.ArrayList;
import java.util.List;

import com.dxhr.platform.framework.core.storage.mongo.exception.BadConfigException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;

/**
 * @author allen.shen
 * @date 2017年4月11日
 * 
 * description:
 * 
 * This MongoFactory is used to new a mongo instance.
 * 
 * If you want to init mongo instance in your spring configure file, do it like
 */
public class MongoFactory {

    private MongoConfig config = new MongoConfig();

    private MongoClient mongo = null;

    private String serverAddressUrls = null;

    public MongoFactory() {

    }

    public MongoFactory(String serverAddress) {
        serverAddressUrls = serverAddress;
    }

    /**
     * Creates a Mongo based on a list of replica set members or a list of
     * mongos. If you have a standalone server, it will use the
     * Mongo(ServerAddress) constructor.
     * 
     * @throws BadConfigException
     */
    public MongoClient newMongoInstance() {

        List<ServerAddress> seeds = getSeeds();

        MongoClientOptions options = null;

        if (config.getBooleanProperty("mongo.options.on", false)) {
            options = initMongoOptions();
        }

        if (seeds.size() > 1) {
            if (options == null)
                mongo = new MongoClient(seeds);
            else
                mongo = new MongoClient(seeds, options);
        } else {
            if (options == null)
                mongo = new MongoClient(seeds.get(0));
            else
                mongo = new MongoClient(seeds.get(0), options);
        }

        return mongo;
    }

    public MongoClient getMongoClientByCredent(String databaseName){  
        MongoClient mongoClient;  
        String user = config.getProperty("username", "test");
        String pswd = config.getProperty("password", "test");  
        List<MongoCredential> credentialList = new ArrayList<MongoCredential>();  
        MongoCredential credential = MongoCredential.createCredential(user, databaseName, pswd.toCharArray());  
        credentialList.add(credential);  
        mongoClient = new MongoClient(getSeeds(), credentialList);  
        return mongoClient;  
    }  

    private List<ServerAddress> getSeeds() {
        String servers = null;
        if (serverAddressUrls == null) {
            servers = config.getProperty("mongo.db.address");
        } else {
            servers = serverAddressUrls;
        }
        if (servers != null && servers.length() > 0) {
            String[] serverArray = servers.split(",");
            String[] host_port = null;
            List<ServerAddress> seeds = new ArrayList<ServerAddress>();
            for (String server : serverArray) {
                host_port = server.split(":");
                try {
                    if (host_port.length == 2) {
                        seeds.add(new ServerAddress(host_port[0], Integer.parseInt(host_port[1])));
                    } else {
                        seeds.add(new ServerAddress(host_port[0], 27017));
                    }
                } catch (NumberFormatException e) {
                    throw new BadConfigException("Bad mongodb port defined : " + host_port[1]);
                }
            }
            return seeds;

        } else {
            throw new BadConfigException("No mongodb host defined!");
        }

    }

    private MongoClientOptions initMongoOptions() {

        MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .socketKeepAlive(true)
                .cursorFinalizerEnabled(true)
                .connectionsPerHost(config.getIntProperty("mongo.options.connectionsPerHost", 10))
                .threadsAllowedToBlockForConnectionMultiplier(
                        config.getIntProperty("mongo.options.threadsAllowedToBlockForConnectionMultiplier", 5))
                .connectTimeout(config.getIntProperty("mongo.options.connectTimeout", 10000))
                .socketTimeout(config.getIntProperty("mongo.options.socketTimeout", 0));

        if (config.getBooleanProperty("mongo.options.readReference.secondary", false)) {
            builder.readPreference(ReadPreference.secondaryPreferred());
        }

        return builder.build();

    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值