package org.springblade.utils;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author: lianghanqiang
 * @description: mongo 连接工具
 * @since: 10/26/21 -- 3:53 PM
 */
@Data
@Slf4j
public class MongoUtils {

	private static MongoClient mongoClient;

	static {
		ClassPathResource resource = new ClassPathResource("mongo.properties");
		Properties properties = new Properties();
		try {
			properties.load(resource.getStream());
			//通过连接认证获取MongoDB连接
			ServerAddress serverAddress = new ServerAddress("192.168.1.218",27017);
			List<ServerAddress> addrs = new ArrayList<ServerAddress>();
			addrs.add(serverAddress);

			//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
			MongoCredential credential = MongoCredential.createScramSha1Credential("root", "ldt", "123456".toCharArray());
			List<MongoCredential> credentials = new ArrayList<MongoCredential>();
			credentials.add(credential);

			//通过连接认证获取MongoDB连接
			mongoClient = new com.mongodb.MongoClient(addrs,credentials);
			System.out.println(JSON.toJSONString(properties));
		} catch (IOException e) {
			log.error("============================== error start ( Mongo connect error ) =====================");
			e.printStackTrace();
			log.error("============================== error end   ( Mongo connect error ) =====================");
		}
	}

	public static void main(String[] args) {
		new MongoUtils();
	}
}
