java mongo的一个初始化写法 - 洪学林个人博客

java mongo的一个初始化写法

@Component
public class MongodbCustomClient {
    private String mongoAddress = SystemConfig.getProperty("mongo.address", "192.168.202.91:27017");

    private int mongoConnectionsPerHost = 100;

    private int mongoThreadsAllowedToBlockForConnectionMultiplier = 5;

    private int mongoConnectionTimeout = 60 * 1000;

    private int mongoMaxWaitTime = 120 * 1000;

    private boolean mongoSocketKeepAlive = true;

    private int mongoSocketTimeout = 0;

    private String auth = SystemConfig.getProperty("mongo.auth", "");

    private String dbName = SystemConfig.getProperty("mongo.dbname", "featureLib");

    private MongoClient mongoClient;


    @PostConstruct
    public void init() {
        MongoClientOptions options = MongoClientOptions.builder()
                .threadsAllowedToBlockForConnectionMultiplier(mongoThreadsAllowedToBlockForConnectionMultiplier)
                .connectTimeout(mongoConnectionTimeout)
                .connectionsPerHost(mongoConnectionsPerHost)
                .maxWaitTime(mongoMaxWaitTime)
                .socketKeepAlive(mongoSocketKeepAlive)
                .writeConcern(WriteConcern.SAFE)
                .socketTimeout(mongoSocketTimeout).build();

        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        String[] auths = auth.split(",");
        for (String a : auths) {
            if (a.equals("")) continue;
            String[] up = a.split(":");
            credentials.add(MongoCredential.createCredential(up[0], dbName, up[1].toCharArray()));
        }

        String[] servers = mongoAddress.split(",");
        List<ServerAddress> addresses = new ArrayList<ServerAddress>();
        for (String server : servers) {
            String[] hp = server.split(":");
            addresses.add(new ServerAddress(hp[0], Integer.valueOf(hp[1])));
        }

        if (credentials.size() > 0) {
            mongoClient = new MongoClient(addresses, credentials, options);
        } else {
            mongoClient = new MongoClient(addresses, options);
        }
    }

    public MongoDatabase getDataBase() {
        return mongoClient.getDatabase(dbName);
    }

    public MongoCollection<Document> getCollection(String collection) {
        return getDataBase().getCollection(collection);
    }

}
添加新评论