首页 > 其他分享 >手动创建mongo连接

手动创建mongo连接

时间:2022-10-05 09:56:24浏览次数:45  
标签:mongoDbConfig return mongo 创建 手动 private import public String

通过读取配置手动创建mongo连接对象

一、配置实体

import com.alibaba.druid.util.StringUtils;
import com.ft.monitoring.dataInterface.common.util.Md5Util;
import com.mongodb.ServerAddress;
import lombok.Data;
import lombok.EqualsAndHashCode;

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

/**
 * Mongodb数据库连接配置
 * database 需要访问的数据库 zxjc
 * authentication 创建用户时指定的配置 db.createUser({ user:'admin',pwd:'123456',roles:[{ role:'dbOwner', db: 'admin'}]});
 * 这里authentication填写为admin 否则无访问权限
 *
 */
@Data
@EqualsAndHashCode(callSuper = false)
public class MongoDbConfig{


    /**
     * 标识符
     */
    private String id;
    /**
     * 配置名称
     */
    private String configName;

    /**
     * 配置类型 6-mongo数据库
     */
    private String configType;


    /**
     * mongo连接地址 支持集群配置 'ip:port','ip:port','ip:port','ip:port'
     */
    private String connectAddress;

    /**
     * 用户名称
     */
    private String userName;

    /**
     * 密码
     */
    private String comWord;

    /**
     * 连接数据库
     */
    private String connectDataBase;

    /**
     * 认证数据库
     */
    private String authenticationDataBase;

    private String mongoDataSourceKey;

    /**
     * 连接地址
     */
    private String url;

    public void setComWord(String comWord) {
        //TODO: 如果密码中含有标点符号 百分比编码方式消除歧义
        this.comWord = comWord;
    }

    public void createMongoDataSourceKey() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.connectAddress);
        sb.append(this.userName);
        sb.append(this.comWord);
        sb.append(this.connectDataBase);
        sb.append(this.authenticationDataBase);
        this.mongoDataSourceKey = Md5Util.getMd5(sb.toString());
    }

    public List<ServerAddress> getAddressList() {
        List<ServerAddress> addresses = new ArrayList<>();
        String[] addressList = connectAddress.split(",");
        for (int i = 0; i < addressList.length; i++) {
            String[] addArray = addressList[i].split(":");
            addresses.add(new ServerAddress(addArray[0], Integer.parseInt(addArray[1])));
        }
        return addresses;
    }

    public String getUrl() {
        if (null == this.url || "".equals(this.url)) {
            String mongo_uri = "mongodb://" + this.userName + ":" + this.comWord + "@" + this.connectAddress + "/" + this.connectDataBase;
            this.url = mongo_uri;
            return this.url;
        }
        return url;
    }

    /**
     * 判定是否需要进行认证
     *
     * @return true 不需要验证
     * @return false 需要验证
     */
    public boolean isNotAuthentication() {
        return StringUtils.isEmpty(userName) && StringUtils.isEmpty(comWord) && StringUtils.isEmpty(authenticationDataBase);
    }

}

二、加载mongo连接对象

package com.ft.monitoring.dataInterface.common.factory;

import com.ft.monitoring.dataInterface.common.util.SpringHelper;
import com.ft.monitoring.dataInterface.configData.MongoDbConfig;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.extern.slf4j.Slf4j;

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

/**
 * mongodb连接创建工厂
 *
 */
@Slf4j
public class MongoDatasourceFactory {

    private MongoDatasourceFactory() {
    }

    private static final MongoDatasourceFactory ME = new MongoDatasourceFactory();

    public static MongoDatasourceFactory me() {
        return ME;
    }

    private final List<String> mongoDbKeys = new ArrayList<String>();

    /**
     * 创建数据源 如果数据源已存在不进行创建
     *
     * @param mongoDbConfig
     */
    public void createDataSource(MongoDbConfig mongoDbConfig) {
        //创建key
        mongoDbConfig.createMongoDataSourceKey();
        if (mongoDbKeys.size() > 0 && mongoDbKeys.contains(mongoDbConfig.getMongoDataSourceKey())) {
            log.warn("当前数据库连接已存在,不进行数据源创建");
            return;
        }
        MongoClient client = null;
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        //设置每个连接地址的最大连接数
        builder.connectionsPerHost(10);
        //设置连接的超时时间
        builder.connectTimeout(5000);
        //设置读写的超时时间
        builder.socketTimeout(5000);

        List<ServerAddress> addresses = mongoDbConfig.getAddressList();
        if (mongoDbConfig.isNotAuthentication()) {
            client = new MongoClient(addresses, builder.build());
        } else {
            MongoCredential credential = MongoCredential.createCredential(mongoDbConfig.getUserName(),
                    mongoDbConfig.getAuthenticationDataBase(), mongoDbConfig.getComWord().toCharArray());
            client = new MongoClient(addresses, credential, builder.build());
        }
        //注入spring
        SpringHelper.registerSingletonBean(mongoDbConfig.getMongoDataSourceKey(), client);
        mongoDbKeys.add(mongoDbConfig.getMongoDataSourceKey());
        log.info("MONGO数据源创建成功:【key:{}】", mongoDbConfig.getMongoDataSourceKey());
    }

    //获取mongo连接
    public MongoClient getMongoClient(String mongoDataSourceKey) {
        MongoClient mongoClient = null;
        if (!mongoDbKeys.contains(mongoDataSourceKey)) {
            log.warn("当前数据源不存在,请创建数据源");
            return null;
        }
        mongoClient = SpringHelper.getBean(mongoDataSourceKey);
        return mongoClient;
    }

}

 

标签:mongoDbConfig,return,mongo,创建,手动,private,import,public,String
From: https://www.cnblogs.com/Sora-L/p/16755096.html

相关文章