The base class implementation of the MongoDB logging operation log

Source: Internet
Author: User
Tags dateformat getmessage mongodb update

    1. Mongodb-context.xml configuration:

<?xml version= "1.0"  encoding= "UTF-8"? >  <beans xmlns= "http// Www.springframework.org/schema/beans "       xmlns:xsi=" http://www.w3.org/ 2001/xmlschema-instance "       xmlns:context=" http// Www.springframework.org/schema/context "        xmlns:mongo=" http// Www.springframework.org/schema/data/mongo "         xsi: Schemalocation= "http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/context        http:// Www.springframework.org/schema/context/spring-context.xsd        http ://www.springframework.org/schema/data/mongo     &nbsP;     http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd ">               <!--  Load the MongoDB property profile  -->    <bean class= " Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ">           <property name= "Locations" >               <list>                   <value>classpath:mongodb.properties</value>               </list>           </property>           <property name= "Ignoreunresolvableplaceholders" &nbSp;value= "true"  />       </bean>           <!--  Define the MONGO object, corresponding to the Mongo,replica-set in the MONGODB official jar package set the IP address and port of the cluster replica  -->    <mongo:mongo id= "MONGO"  replica-set= "${mongo.hostport}" >         <!--  Settings for some connection properties  -->             <mongo:options connections-per-host= "${ Mongo.connectionsperhost} " />             </mongo:mongo>    <mongo:db-factory id= "Mongodbfactory"  dbname= "${ Mongo.database} "     mongo-ref=" MONGO " username=" ${mongo.username} "  Password= "${mongo.password}"  />        <bean id= " Mongotemplate " class=" Org.springframework.data.monGodb.core.MongoTemplate ">        <constructor-arg name=" Mongodbfactory " ref=" Mongodbfactory "/>    </bean>         <bean id= "Mongobase"  class= "Com.oplog.db.MongoBase" >      <property name= "Mongotemplate"  ref= "Mongotemplate"/>    </ Bean></beans>

2. #mongodb. Properties Configuration

Mongo.hostport=127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019mongo.database=operationlogmongo.username= mongousermongo.password=123456!mongo.connectionsperhost=8mongo.threadsallowedtoblockforconnectionmultiplier=4# Connection Timeout time mongo.connecttimeout=1000# wait time mongo.maxwaittime=1500mongo.autoconnectretry=truemongo.socketkeepalive= True#socket Timeout Time Mongo.sockettimeout=1500mongo.slaveok=true

3. Code:

package com.oplog.db;import java.text.simpledateformat;import java.util.arraylist;import  java.util.date;import java.util.list;import java.util.map;import javax.annotation.resource; Import org.bson.types.objectid;import org.slf4j.logger;import org.slf4j.loggerfactory;import  org.springframework.data.mongodb.core.MongoTemplate;import com.mongodb.BasicDBObject;import  com.mongodb.db;import com.mongodb.dbcollection;import com.mongodb.dbcursor;import  Com.mongodb.dbobject;public  class mongobase {private static final logger  logger = loggerfactory.getlogger (mongobase.class);p rotected string database; Protected static final simpledateformat dateformat = new simpledateformat (" Yyyy-mm-dd hh:mm:ss "), @Resource (name=" mongotemplate ") private mongotemplate mongotemplate;public  mongobase ()  {}public mongotEmplate getmongotemplate ()  {return mongotemplate;} Public void setmongotemplate (mongotemplate mongotemplate)  {this.mongoTemplate =  Mongotemplate;} /** *  get database objects based on database name  *  @param  DBName *  @return  */protected db  getmongodb (string dbname) {return mongotemplate.getdb ();} /** *  inserting data  *  @param  table *  @param  params *  @return  */ Protected boolean insert (string table,map<string,object> params ) {boolean  Result=true;try {string uniqueid = getid ();p arams.put ("_id",  uniqueid); Basicdbobject datas = new basicdbobject (params);D B db = this.getmongodb ( database);D bcollection tableobj = db.getcollection (table); Tableobj.insert (datas);}  catch  (exception e)  {logger.error ("Insert data into MongoDB error, Database name:"  +  database +  ", table:"  + table +  ", params:"  + params+ ", insert errmsg:" + E.getmessage ()); result=false;} Return result;} /** *  query Data  *  @param  table *  @param  params *  @param   Start start position  *  @param  size  number of queries  *  @return  */protected List<Map< String,object>> query (string table,map<string,object> params,int start,  Int size) {list<map<string,object>> result=new arraylist<map<string,object> > Try {basicdbobject conditions = new basicdbobject (params);D b db =  this.getmongodb (database);D bcollection tableobj = db.getcollection (table);D bcursor  Cursor=tableobj.find (conditions). Skip (start). Limit (size). Sort (New basicdbobject ("_id", -1)); while ( Cursor.hasnext ()) {Dbobject item=cursor.next ();p rocessqueryresult (Item,result);}}  catch  (exception e)  {logger.error ("Error querying data from MongoDB, Database name:"  + database +   ", table:"  + table +  ", params:"  + params+ ", Start:" +start+ ", Size:" +size+ ", Querylist errmsg: "+e.getmessage ());} Return result;} Protected long querycount (String table,map<string,object> params) {long  Totalcount=0;try{basicdbobject conditions = new basicdbobject (params);D b db =  this.getmongodb (database);D bcollection tableobj = db.getcollection (table); totalcount= Tableobj.count (conditions);} catch (exception e) {logger.error ("error querying total data from MongoDB, Database name:"  + database +  " , table: " + table + ", params: " + params+", Querycount: "+e.getmessage ());} Return totalcount;} Protected boolean update (String table,map<string,object> params,map<string,object > updatedata) {boolean Result=true;try{basicdbobject condtions=new basicdbobject (params); Basicdbobject datas=new basicdbobject (UpdateData);D b db=this.getmongodb (database);D bcollection  tableobj=db.getcollection (table); Int count=tableobj.update (Condtions, new basicdbobject (" $set ", datas), false,true). GETN (); if (count<1) {result=false;logger.info (" MongoDB Update data failed, Database name: "  + database +  ", table:"  + table +  ", params:"  + params+ ", UpdateData: "+updatedata);}} catch (exception e) {logger.error ("MongoDB modified data error, Database name:"  + database +  ", Table: " + table + ", params: " + params+", UpdateData: "+updatedata+",update  ErrMsg: "+e.getmessage ()); result=false;} Return result;} Protected boolean deleleone (String table,map<string,object> params) {boolean  Result=true;try{basicdbobject conditions=new basicdbobject (params);D B&nbsP;db=this.getmongodb (database);D bcollection tableobj=db.getcollection (table); int count= Tableobj.remove (conditions). GETN (), if (count<1) {result=false;logger.info ("delete data from MongoDB failed, Database name: " + database + ", Table: " + table + ", params: " + params);}} catch (exception e) {logger.error ("error deleting data from MongoDB, Database name:"  + database +  ", Table: " + table + ", params: " + params+", Deleteone errmsg: "+e.getmessage ()); Result=false;} Return result;} /** *  gets the primary key  *  @return  */protected string getid () {return objectid.get (). ToString ();} Protected string getdatabase ()  {return database;} Protected void setdatabase (String database)  {this.database = database;} @SuppressWarnings ("Unchecked") Private void processqueryresult (dbobject item,list<map< String,object>> result){if (Null==item) {return;}     for (String key:item.keyset ()) {    object value=item.get ( key);     if (value instanceof date) {    date datevalue= ( Date) Value;    string datestr=dateformat.format (dateValue);     Item.put (KEY,DATESTR);     }    }    result.add ( Item.tomap ());}}


This article from "Quiet Zhiyuan" blog, declined reprint!

The base class implementation of the MongoDB logging operation log

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.