자바 조작 mongodb3. x

6958 단어
더 읽 기

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);
		}

	}
}

좋은 웹페이지 즐겨찾기