MongoDB thread-Safe batch processing

Source: Internet
Author: User
Tags log log solr

MONGO Batch processing tool class:

 PackageCom.saike.solr.server.util;Importjava.net.UnknownHostException;Importjava.util.ArrayList;ImportCom.mongodb.BasicDBObject;ImportCom.mongodb.DB;Importcom.mongodb.DBCollection;ImportCom.mongodb.DBCursor;ImportCom.mongodb.DBObject;ImportCom.mongodb.Mongo;Importcom.mongodb.MongoException;Importcom.mongodb.MongoOptions;/*** Batch processing tool class *@authorXieyong **/ Public classutilemongdb {utilthreadlocal<ArrayList<DBObject>>Localbatch; /**MONGO Singleton Object according to official document Mongojava is thread-safe*/    Private StaticMongo Mongo; Private StaticDbcollection Coll; //private static log log = Logfactory.getlog (Utilemongdb.class);    Private StaticDB DB; Static{           /**Instantiate DB*/mongooptions Options=Newmongooptions (); Options.autoconnectretry=true; Options.connectionsperhost= 1000; Options.maxwaittime= 5000; Options.sockettimeout= 0; Options.connecttimeout= 15000; Options.threadsallowedtoblockforconnectionmultiplier= 5000; Try{MONGO=NewMongo (Mongodbconstant.mongo_host,mongodbconstant.mongo_port); } Catch(Unknownhostexception |mongoexception e)            {E.printstacktrace (); }            //Boolean auth = Db.authenticate (myusername, mypassword);    }         Publicutilemongdb () {Try{Localbatch=NewUtilthreadlocal<arraylist<dbobject>> (ArrayList.class); } Catch(Exception e) {e.printstacktrace (); }     }    /*** Return DB Object *@returnDB*/     Public StaticDB Getdb () {if(db==NULL) {db=Mongo.getdb (mongodbconstant.mongo_db); }        returnDB; }        /*** Return to MONGO *@returnMONGO Connection Pool*/     Public StaticMongo Getmong () {returnMONGO; }        /*** Read Collection *@returnMONGO Collection **/     Public Staticdbcollection getcoll (String collname) {returnGetdb (). GetCollection (Collname); }         Public Staticdbcollection Getcoll () {returnGetdb (). GetCollection (mongodbconstant.mongo_collection); }        /**crud Operations*/     Public voidAddbatch (String key,string value) {Basicdbobject basicdb=NewBasicdbobject ();        Basicdb.put (key, value); /**This is a thread-local variable, and there are no competitive conditions.*/Localbatch.newget (). Add (BASICDB); }        /*** Perform batch processing **/     Public voidExecuteinsertbatch () {getcoll (). Insert (Localbatch.get ());    Localbatch.get (). Clear (); }    /*** Perform bulk delete*/     Public voidExecutedeletebatch () {ArrayList<DBObject> array =Localbatch.get ();  for(DBObject obj:array) {getcoll (). Remove (obj);    } localbatch.get (). Clear (); }                         Publicdbcursor Query (String key,string value) {Basicdbobject Basicdbobject=NewBasicdbobject ();        Basicdbobject.put (Key,value); returnGetcoll (). Find (Basicdbobject); }        }

Threadlocal Package:

 PackageCom.saike.solr.server.util;ImportJava.lang.reflect.Constructor;/** *  * @authorXieyong * *@param<T> types of local thread variable objects*/ Public classUtilthreadlocal<t>extendsThreadlocal<t> {    /**Parameter Collection*/object[] obj; /**Instantiating Constructors*/Constructor<T>construct; /**     *      * @paramClazz class * for local variables@paramparameters of the args constructor *@throwsnosuchmethodexception *@throwsSecurityException*/     PublicUtilthreadlocal (Class clazz,object ... args)throwsnosuchmethodexception, securityexception{ This. obj =obj; Class[] Clazzs=NULL; /**new Gets the argument class for the get constructor*/        if(Args! =NULL)            if(Args.length!=0) {Clazzs=NewClass[args.length];  for(inti = 0;i<args.length;i++) {Clazzs[i]=Args[i].getclass (); }            }         This. construct =Clazz.getconstructor (Clazzs); }        /*** If the current thread does not have an object to create a new object *@return     */     PublicT Newget () {T tar=Super. get (); if(Tar = =NULL){            Try{tar=construct.newinstance (obj); Super. Set (TAR); }Catch(Exception e) {e.printstacktrace (); }        }        returntar; }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.