mongoDB 实现主从读写分离实现的实例代码
mongoDB主从读写分离
MongoDB官方已经不建议使用主从模式了,替代方案是采用副本集的模式,点击查看。如果您的环境不符合副本集模式可参考本文,来实现主从读写分离。
resources.properties
mongodb_read.host=10.0.0.45 mongodb_read.port=27017 mongodb_read.apname=ecsp mongodb_read.username= mongodb_read.password= mongodb_write.host=10.0.0.46 mongodb_write.port=27017 mongodb_write.apname=ecsp mongodb_write.username= mongodb_write.password=
mongo_config.xml
<beansxmlns="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/context http://www.springframework.org/schema/context/spring-context-2.0.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <!--连接数据库信息--> <beanid="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <propertyname="locations"> <list> <value>classpath:resources.properties</value> </list> </property> </bean> <!--读start--> <beanid="mongoServerReadAddress"class="com.mongodb.ServerAddress"> <constructor-argvalue="${mongodb_read.host}"></constructor-arg> <constructor-argvalue="${mongodb_read.port}"></constructor-arg> </bean> <beanid="chexunMongoReadOptions"class="com.ecsp.chexun.mongo.ChexunMongoOptions"> <propertyname="username"value="${mongodb_read.username}"/> <propertyname="password"value="${mongodb_read.password}"/> <propertyname="dbname"value="${mongodb_read.apname}"/> <propertyname="connectionsPerHost"value="100"/> <propertyname="threadsAllowedToBlockForConnectionMultiplier" value="5"/> <propertyname="slaveOk"value="true"/> </bean> <beanid="mongo_read"class="com.mongodb.Mongo"> <constructor-argref="mongoServerReadAddress"></constructor-arg> <constructor-argref="chexunMongoReadOptions"></constructor-arg> </bean> <!--读end--> <!--写start--> <beanid="mongoServerWriteAddress"class="com.mongodb.ServerAddress"> <constructor-argvalue="${mongodb_write.host}"></constructor-arg> <constructor-argvalue="${mongodb_write.port}"></constructor-arg> </bean> <beanid="chexunMongoWriteOptions"class="com.ecsp.chexun.mongo.ChexunMongoOptions"> <propertyname="username"value="${mongodb_write.username}"/> <propertyname="password"value="${mongodb_write.password}"/> <propertyname="dbname"value="${mongodb_write.apname}"/> <propertyname="connectionsPerHost"value="100"/> <propertyname="threadsAllowedToBlockForConnectionMultiplier" value="5"/> </bean> <beanid="mongo_write"class="com.mongodb.Mongo"> <constructor-argref="mongoServerWriteAddress"></constructor-arg> <constructor-argref="chexunMongoWriteOptions"></constructor-arg> </bean> <!--写end--> <!--链接对象注入start--> <beanid="mongoHelper"class="com.ecsp.chexun.mongo.MongoHelper"> <constructor-argref="mongo_read"></constructor-arg> <constructor-argref="mongo_write"></constructor-arg> </bean> <!--链接对象注入end--> </beans>
web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/classes/mongo_config.xml </param-value> </context-param>
实体层ChexunMongoOptions.Java
packagecom.ecsp.chexun.mongo; importjavax.net.SocketFactory; importcom.mongodb.DBDecoderFactory; importcom.mongodb.MongoOptions; /** *Mongo配置类 * *@authorvincent.he *@version1.0,Createdon2012-3-12 * */ publicclassChexunMongoOptionsextendsMongoOptions{ privateStringusername; privateStringpassword; privateStringdbname; publicChexunMongoOptions(){ super(); } publicvoidsetDescription(Stringdescription){ this.description=description; } publicvoidsetConnectionsPerHost(intconnectionsPerHost){ this.connectionsPerHost=connectionsPerHost; } publicvoidsetThreadsAllowedToBlockForConnectionMultiplier( intthreadsAllowedToBlockForConnectionMultiplier){ this.threadsAllowedToBlockForConnectionMultiplier=threadsAllowedToBlockForConnectionMultiplier; } publicvoidsetMaxWaitTime(intmaxWaitTime){ this.maxWaitTime=maxWaitTime; } publicvoidsetConnectTimeout(intconnectTimeout){ this.connectTimeout=connectTimeout; } publicvoidsetSocketTimeout(intsocketTimeout){ this.socketTimeout=socketTimeout; } publicvoidsetSocketKeepAlive(booleansocketKeepAlive){ this.socketKeepAlive=socketKeepAlive; } publicvoidsetAutoConnectRetry(booleanautoConnectRetry){ this.autoConnectRetry=autoConnectRetry; } publicvoidsetMaxAutoConnectRetryTime(longmaxAutoConnectRetryTime){ this.maxAutoConnectRetryTime=maxAutoConnectRetryTime; } publicvoidsetSlaveOk(booleanslaveOk){ this.slaveOk=slaveOk; } publicvoidsetDbDecoderFactory(DBDecoderFactorydbDecoderFactory){ this.dbDecoderFactory=dbDecoderFactory; } publicvoidsetSafe(booleansafe){ this.safe=safe; } publicvoidsetW(intw){ this.w=w; } publicvoidsetWtimeout(intwtimeout){ this.wtimeout=wtimeout; } publicvoidsetFsync(booleanfsync){ this.fsync=fsync; } publicvoidsetJ(booleanj){ this.j=j; } publicvoidsetSocketFactory(SocketFactorysocketFactory){ this.socketFactory=socketFactory; } publicStringgetUsername(){ returnusername; } publicvoidsetUsername(Stringusername){ this.username=username; } publicStringgetPassword(){ returnpassword; } publicvoidsetPassword(Stringpassword){ this.password=password; } publicStringgetDbname(){ returndbname; } publicvoidsetDbname(Stringdbname){ this.dbname=dbname; } }
Javadao层
packagecom.ecsp.chexun.mongo; importjava.util.List; importcom.mongodb.BasicDBObject; importcom.mongodb.CommandResult; importcom.mongodb.DB; importcom.mongodb.DBCollection; importcom.mongodb.DBObject; importcom.mongodb.Mongo; /** *mongo操做方法 *@authorzhanglibing * */ publicclassMongoHelper{ privateMongomongo; privateMongomongo_read; privateMongomongo_write; privateStringdataBaseName="cxec"; publicMongoHelper(){} publicMongoHelper(Mongomongo,Mongomongo_read,Mongomongo_write){ this.mongo=mongo; this.mongo_read=mongo_read; this.mongo_write=mongo_write; } //publicMongoHelper(StringdbName){ //dataBaseName=dbName; //} publicintadd(StringcollectionName,BasicDBObjectdbObject){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_write.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.save(dbObject).getN(); } //批量添加 publicintaddAll(StringcollectionName,List<DBObject>list){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_write.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.insert(list).getN(); } publicintisExists(StringcollectionName,BasicDBObjectquery){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query).size(); } publicList<DBObject>get(StringcollectionName,BasicDBObjectquery){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query).toArray(); } publicintgetCount(StringcollectionName,BasicDBObjectquery){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query).count(); } publicList<DBObject>get(StringcollectionName,BasicDBObjectquery,BasicDBObjectkeys){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query,keys).toArray(); } /*** *获取mongo中collection的值 *@paramcollectionName *@paramquery查询条件 *@paramkeys查询字段 *@parambatchSize返回个数 *@return */ publicList<DBObject>get(StringcollectionName,BasicDBObjectquery,BasicDBObjectkeys,BasicDBObjectorderBy,intbatchSize){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); if(orderBy!=null){ returndbc.find(query,keys).sort(orderBy).limit(batchSize).toArray(); } returndbc.find(query,keys).limit(batchSize).toArray(); } publicList<DBObject>get(StringcollectionName,BasicDBObjectquery,BasicDBObjectkeys,BasicDBObjectorderBy,intbatchSize,intn){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); if(orderBy!=null){ returndbc.find(query,keys).sort(orderBy).limit(batchSize).skip(n).toArray(); } returndbc.find(query,keys).limit(batchSize).toArray(); } publicList<DBObject>get(StringcollectionName,DBObjectquery,intbatchSize){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query).limit(batchSize).toArray(); } publicList<DBObject>get(StringcollectionName,intnumber){ DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); List<DBObject>dboList=dbc.find().skip(0).limit(number).toArray(); returndboList; } publicList<DBObject>get(StringcollectionName,BasicDBObjectquery,BasicDBObjectorderBy,intn,intpageSize){ DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); List<DBObject>dboList=dbc.find(query).sort(orderBy).skip(n).limit(pageSize).toArray(); returndboList; } publicList<DBObject>get(StringcollectionName,BasicDBObjectquery,inttop){ DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); List<DBObject>dboList=dbc.find(query).skip(0).limit(top).toArray(); returndboList; } publicList<DBObject>get(StringcollectionName,DBObjectquery,DBObjectorderBy,intbatchSize){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_read.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.find(query).sort(orderBy).limit(batchSize).toArray(); } publicintreomve(StringcollectionName,BasicDBObjecto){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_write.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.remove(o).getN(); } publicintedit(StringcollectionName,BasicDBObjectquery,BasicDBObjectupdate){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo_write.getDB(dataBaseName); DBCollectiondbc=db.getCollection(collectionName); returndbc.update(query,update).getN(); //returndbc.updateMulti(query,update).getN(); } publicintedit(Stringcmd){ //DBdb=MongoManager.getDB(dataBaseName); DBdb=mongo.getDB(dataBaseName); CommandResultcmdResult=db.command(cmd); if(cmdResult.ok()) { return1; } return0; } //publicDBCollectionget(StringcollectionName){ ////DBdb=MongoManager.getDB(dataBaseName); //DBdb=mongo.getDB(dataBaseName); //returndb.getCollection(collectionName); //} publicvoidsetMongo(Mongomongo){ this.mongo=mongo; } publicvoidsetMongo_read(Mongomongo_read){ this.mongo_read=mongo_read; } publicvoidsetMongo_write(Mongomongo_write){ this.mongo_write=mongo_write; } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!