- mongodb-context.xml配置:
<?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 http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> <!-- 加载mongodb的属性配置文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:mongodb.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 --> <mongo:mongo id="mongo" replica-set="${mongo.hostport}"> <!-- 一些连接属性的设置 --> <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配置
mongo.hostport=127.0.0.1:27017,127.0.0.1:27018,127.0.0.1:27019 mongo.database=operationlog mongo.username=mongouser mongo.password=123456! mongo.connectionsPerHost=8 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #连接超时时间 mongo.connectTimeout=1000 #等待时间 mongo.maxWaitTime=1500 mongo.autoConnectRetry=true mongo.socketKeepAlive=true #Socket超时时间 mongo.socketTimeout=1500 mongo.slaveOk=true
3.代码:
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); protected 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; } /** * 根据数据库名称获取数据库对象 * @param DBName * @return */ protected DB getMongoDB(String DBName){ return mongoTemplate.getDb(); } /** * 插入数据 * @param table * @param params * @return */ protected boolean insert(String table,Map<String,Object> params ){ boolean result=true; try { String uniqueId = getId(); params.put("_id", uniqueId); BasicDBObject datas = new BasicDBObject(params); DB db = this.getMongoDB(database); DBCollection tableObj = db.getCollection(table); tableObj.insert(datas); } catch (Exception e) { logger.error("插入数据到mongodb出错,database name:" + database + ",table:" + table + ",params:" + params+",insert errmsg:"+e.getMessage()); result=false; } return result; } /** * 查询数据 * @param table * @param params * @param start 起始位置 * @param size 查询数量 * @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); DB db = this.getMongoDB(database); DBCollection tableObj = db.getCollection(table); DBCursor cursor=tableObj.find(conditions).skip(start).limit(size).sort(new BasicDBObject("_id",-1)); while(cursor.hasNext()){ DBObject item=cursor.next(); processQueryResult(item,result); } } catch (Exception e) { logger.error("从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); DB db = this.getMongoDB(database); DBCollection tableObj = db.getCollection(table); totalcount=tableObj.count(conditions); }catch(Exception e){ logger.error("从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); DB db=this.getMongoDB(database); DBCollection tableObj=db.getCollection(table); int count=tableObj.update(condtions, new BasicDBObject("$set",datas),false,true).getN(); if(count<1){ result=false; logger.info("mongodb更新数据失败,database name:" + database + ",table:" + table + ",params:" + params+",updatedata:"+updateData); } }catch(Exception e){ logger.error("mongodb修改数据出错,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); DB db=this.getMongoDB(database); DBCollection tableObj=db.getCollection(table); int count=tableObj.remove(conditions).getN(); if(count<1){ result=false; logger.info("从mongodb删除数据失败,database name:" + database + ",table:" + table + ",params:" + params); } }catch(Exception e){ logger.error("从mongodb删除数据出错,database name:" + database + ",table:" + table + ",params:" + params+",deleteone errmsg:"+e.getMessage()); result=false; } return result; } /** * 获取主键 * @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()); } }
时间: 2024-10-26 20:45:04