java 操作mongodb3.x

阅读更多
package com.labci.mongodb.test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.poi.ss.formula.functions.T;
import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.robustel.iot.data.parse.entity.DeviceCommunicationModuleData;
import com.robustel.pl.util.utils.UUIDUtil;

/**
 * 功能说明:java链接操作mongodb
 * 
 *         思路:1.建立连接并验证 2.获取一个集合列表 3.获取选择第一
 * 个集合 4.插入集合 5.查询集合
 */
public class MongodbTest {
	
	static List companyIds = new ArrayList(500);
	
	static List deviceIds = new ArrayList(20000);
	static MongodbTest mo = new MongodbTest();
	static MongoDatabase db = mo.connectMongoDB("link_user", "rlink", "123456".toCharArray());
	
    /**
     * 连接mongodb数据库服务,验证用户名密码
     * 
     * @return
     */
    private MongoDatabase connectMongoDB(String name, String databaseName, char[] pswd)
    {
        //创建个 credential对象
        MongoCredential credential = MongoCredential.createCredential(name, databaseName, pswd);
        //把对象传入mongoClient的构造方法中,说明:用户名密码端口啥的都正确会得到mongoClient,否则程序会报错
        //mongodb还有很多种验证方式 详见:http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/authenticating/ 
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.16.7.110", 27017), Arrays.asList(credential));
        MongoDatabase db = mongoClient.getDatabase("rlink");
        return db;
    }

    /**
     * 获取一个文档
     * 
     * @param db
     */
    private MongoCollection getDBCollection(MongoDatabase db, String setName)
    {
        MongoIterable cols = db.listCollectionNames();
        for (String c : cols)
        {
            System.out.println("collectionName: " + c);
        }
        MongoCollection col = db.getCollection(setName);
        if (col != null)
            return col;
        else
            return null;
    }

    /**
     * 插入一条数据
     * 
     * @param col
     * @param username
     * @param password
     */
    private void insertCollection(MongoCollection col, String username, String password)
    {
        Document doc =new Document();
        doc.put("usename", username);
        doc.put("password", password);
        col.insertOne(doc);
        ;
    }
    
    private void insertMany(MongoCollection col, 
    		List documents){
        col.insertMany(documents);
    }

    /**
     * 查找一个doc
     * 
     * @param colName
     */
    private void findColByColName(MongoCollection doc)
    {
        FindIterable mydoc = doc.find();
        for (Document d : mydoc)
        {
            System.out.println(d.toJson());
            System.out.println(d.toString());
        }
    }
    
	
	public static String randomLonLat(double MinLon, double MaxLon, double MinLat, double MaxLat, String type) {
	    Random random = new Random();
	    BigDecimal db = new BigDecimal(Math.random() * (MaxLon - MinLon) + MinLon);
	    String lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();// 小数后6位
	    db = new BigDecimal(Math.random() * (MaxLat - MinLat) + MinLat);
	    String lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
	    if (type.equals("Lon")) {
	      return lon;
	    } else {
	      return lat;
	    }
	  }

    public static void main(String[] args){
        
    	for(int i=0;i<500;i++){
			companyIds.add(UUIDUtil.getKeys());
		}
		
		for(int i=0;i<20000;i++){
			deviceIds.add(UUIDUtil.getKeys());
		}
		
		Integer count = 200000;
		Integer betch = 1000;
		Random random = new Random();
		
		ExecutorService exec = Executors.newFixedThreadPool(150);

		while(count >0 ){
			exec.execute(new MongodbWork(count,betch,random,exec));
			count--;
		}
       
    }
    
    static class MongodbWork implements Runnable {
		Integer count;
		Random random;
		ExecutorService exec;
		Integer betch;
		String collectionName = "gps";
		
		public MongodbWork(Integer count,Integer betch,Random random,ExecutorService exec){
			this.count = count;
			this.betch = betch;
			this.random = random;
			this.exec = exec;
		}
		
		@Override
		public void run() {
			
				System.out.println(Thread.currentThread().getName() +"---"+count +"----"+betch+"---"+count);
				
				List arrays = new ArrayList(betch);
				
				for(int i=0;i< betch;i++){
					Document mongoEntry =new Document();
					
					mongoEntry.put("companyId",companyIds.get(random.nextInt(companyIds.size())));
					mongoEntry.put("id",UUIDUtil.getKeys());
					mongoEntry.put("createTime",new Date());
					mongoEntry.put("deviceId",deviceIds.get(random.nextInt(deviceIds.size())));
					mongoEntry.put("moduleCode","gps");
					mongoEntry.put("deviceTime",new Date().getTime());
					
					Map maps = new HashMap();
					maps.put("longitude", randomLonLat(0, 2000, 0, 3000, "Lon"));
					maps.put("latitude", randomLonLat(0, 2000, 0, 3000, "Lat"));
					
					mongoEntry.put("fieldValue",maps);
					arrays.add(mongoEntry);
				}
				
				MongoCollection doc = mo.getDBCollection(db, collectionName);
				mo.insertMany(doc, arrays);
		}

	}
}

你可能感兴趣的:(java 操作mongodb3.x)