服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - mongoDB 实现主从读写分离实现的实例代码

mongoDB 实现主从读写分离实现的实例代码

2020-05-10 17:16LQH MongoDB

这篇文章主要介绍了 mongoDB 实现主从读写分离实现的实例代码的相关资料,需要的朋友可以参考下

mongoDB主从读写分离

MongoDB官方已经不建议使用主从模式了,替代方案是采用副本集的模式, 点击查看。如果您的环境不符合副本集模式可参考本文,来实现主从读写分离。

resources.properties

?
1
2
3
4
5
6
7
8
9
10
11
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<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/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">
 
  <!-- 连接数据库信息 -->
  <bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath:resources.properties</value>
      </list>
    </property>
  </bean>
  <!-- 读start -->
  <bean id="mongoServerReadAddress" class="com.mongodb.ServerAddress">
    <constructor-arg value="${mongodb_read.host}"></constructor-arg>
    <constructor-arg value="${mongodb_read.port}"></constructor-arg>
  </bean>
  <bean id="chexunMongoReadOptions" class="com.ecsp.chexun.mongo.ChexunMongoOptions">
    <property name="username" value="${mongodb_read.username}" />
    <property name="password" value="${mongodb_read.password}" />
    <property name="dbname" value="${mongodb_read.apname}" />
    <property name="connectionsPerHost" value="100" />
    <property name="threadsAllowedToBlockForConnectionMultiplier"
      value="5" />
    <property name="slaveOk" value="true" />
  </bean>
  <bean id="mongo_read" class="com.mongodb.Mongo">
    <constructor-arg ref="mongoServerReadAddress"></constructor-arg>
    <constructor-arg ref="chexunMongoReadOptions"></constructor-arg>
  </bean>
  <!-- 读end -->
 
  <!-- 写start -->
  <bean id="mongoServerWriteAddress" class="com.mongodb.ServerAddress">
    <constructor-arg value="${mongodb_write.host}"></constructor-arg>
    <constructor-arg value="${mongodb_write.port}"></constructor-arg>
  </bean>
  <bean id="chexunMongoWriteOptions" class="com.ecsp.chexun.mongo.ChexunMongoOptions">
    <property name="username" value="${mongodb_write.username}" />
    <property name="password" value="${mongodb_write.password}" />
    <property name="dbname" value="${mongodb_write.apname}" />
    <property name="connectionsPerHost" value="100" />
    <property name="threadsAllowedToBlockForConnectionMultiplier"
      value="5" />
  </bean>
  <bean id="mongo_write" class="com.mongodb.Mongo">
    <constructor-arg ref="mongoServerWriteAddress"></constructor-arg>
    <constructor-arg ref="chexunMongoWriteOptions"></constructor-arg>
  </bean>
  <!-- 写end -->
 
  <!-- 链接对象注入start -->
  <bean id="mongoHelper" class="com.ecsp.chexun.mongo.MongoHelper">
    <constructor-arg ref="mongo_read"></constructor-arg>
    <constructor-arg ref="mongo_write"></constructor-arg>
  </bean>
 
  <!-- 链接对象注入end -->
</beans>

web.xml

?
1
2
3
4
5
6
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/classes/mongo_config.xml
  </param-value>
</context-param>

实体层ChexunMongoOptions.Java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package com.ecsp.chexun.mongo;
 
import javax.net.SocketFactory;
 
import com.mongodb.DBDecoderFactory;
import com.mongodb.MongoOptions;
 
/**
 * Mongo配置类
 *
 * @author vincent.he
 * @version 1.0, Created on 2012-3-12
 *
 */
public class ChexunMongoOptions extends MongoOptions{
  private String username;
  private String password;
  private String dbname;
 
  public ChexunMongoOptions(){
    super();
  }
 
  public void setDescription(String description) {
    this.description = description;
  }
 
  public void setConnectionsPerHost(int connectionsPerHost) {
    this.connectionsPerHost = connectionsPerHost;
  }
 
  public void setThreadsAllowedToBlockForConnectionMultiplier(
      int threadsAllowedToBlockForConnectionMultiplier) {
    this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
  }
 
  public void setMaxWaitTime(int maxWaitTime) {
    this.maxWaitTime = maxWaitTime;
  }
 
  public void setConnectTimeout(int connectTimeout) {
    this.connectTimeout = connectTimeout;
  }
 
  public void setSocketTimeout(int socketTimeout) {
    this.socketTimeout = socketTimeout;
  }
 
  public void setSocketKeepAlive(boolean socketKeepAlive) {
    this.socketKeepAlive = socketKeepAlive;
  }
 
  public void setAutoConnectRetry(boolean autoConnectRetry) {
    this.autoConnectRetry = autoConnectRetry;
  }
 
  public void setMaxAutoConnectRetryTime(long maxAutoConnectRetryTime) {
    this.maxAutoConnectRetryTime = maxAutoConnectRetryTime;
  }
 
  public void setSlaveOk(boolean slaveOk) {
    this.slaveOk = slaveOk;
  }
 
  public void setDbDecoderFactory(DBDecoderFactory dbDecoderFactory) {
    this.dbDecoderFactory = dbDecoderFactory;
  }
 
  public void setSafe(boolean safe) {
    this.safe = safe;
  }
 
  public void setW(int w) {
    this.w = w;
  }
 
  public void setWtimeout(int wtimeout) {
    this.wtimeout = wtimeout;
  }
 
  public void setFsync(boolean fsync) {
    this.fsync = fsync;
  }
 
  public void setJ(boolean j) {
    this.j = j;
  }
 
  public void setSocketFactory(SocketFactory socketFactory) {
    this.socketFactory = socketFactory;
  }
 
  public String getUsername() {
    return username;
  }
 
  public void setUsername(String username) {
    this.username = username;
  }
 
  public String getPassword() {
    return password;
  }
 
  public void setPassword(String password) {
    this.password = password;
  }
 
  public String getDbname() {
    return dbname;
  }
 
  public void setDbname(String dbname) {
    this.dbname = dbname;
  }
}

Java dao层

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package com.ecsp.chexun.mongo;
import java.util.List;
 
 
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
 
/**
 * mongo 操做方法
 * @author zhanglibing
 *
 */
public class MongoHelper {
 
  private Mongo mongo;
  private Mongo mongo_read;
  private Mongo mongo_write;
  private String dataBaseName = "cxec";
  public MongoHelper(){}
  public MongoHelper(Mongo mongo,Mongo mongo_read,Mongo mongo_write){
    this.mongo = mongo;
    this.mongo_read = mongo_read;
    this.mongo_write = mongo_write;
  }
// public MongoHelper(String dbName){
//   dataBaseName = dbName;  
// }
  public int add(String collectionName,BasicDBObject dbObject){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_write.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.save(dbObject).getN();
  }
  //批量添加
  public int addAll( String collectionName,List<DBObject> list){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_write.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.insert(list).getN();
  }
 
  public int isExists(String collectionName,BasicDBObject query){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.find(query).size();  
  }
 
  public List<DBObject> get(String collectionName,BasicDBObject query){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.find(query).toArray();
  }
 
  public int getCount(String collectionName,BasicDBObject query){   
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.find(query).count();   
  }
 
  public List<DBObject> get(String collectionName,BasicDBObject query,BasicDBObject keys){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.find(query, keys).toArray();
  }
 
  /***
   * 获取mongo 中 collection 的值
   * @param collectionName
   * @param query 查询条件
   * @param keys  查询字段
   * @param batchSize 返回个数
   * @return
   */
  public List<DBObject> get(String collectionName,BasicDBObject query,BasicDBObject keys,BasicDBObject orderBy,int batchSize){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    if(orderBy != null){
      return dbc.find(query, keys).sort(orderBy).limit(batchSize).toArray();
    }
    return dbc.find(query, keys).limit(batchSize).toArray();
  }
 
  public List<DBObject> get(String collectionName,BasicDBObject query,BasicDBObject keys,BasicDBObject orderBy,int batchSize,int n){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    if(orderBy != null){
      return dbc.find(query, keys).sort(orderBy).limit(batchSize).skip(n).toArray();
    }
    return dbc.find(query, keys).limit(batchSize).toArray();
  }
 
  public List<DBObject> get(String collectionName,DBObject query,int batchSize){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);     
    return dbc.find(query).limit(batchSize).toArray();
  }
  public List<DBObject> get(String collectionName,int number){
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName); 
    List<DBObject> dboList = dbc.find().skip(0).limit(number).toArray();
    return dboList;
  }
  public List<DBObject> get(String collectionName,BasicDBObject query,BasicDBObject orderBy,int n,int pageSize ){
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName); 
    List<DBObject> dboList = dbc.find(query).sort(orderBy).skip(n).limit(pageSize).toArray();
    return dboList;
  }
  public List<DBObject> get(String collectionName,BasicDBObject query,int top ){
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName); 
    List<DBObject> dboList = dbc.find(query).skip(0).limit(top).toArray();
 
    return dboList;
  }
  public List<DBObject> get(String collectionName,DBObject query,DBObject orderBy,int batchSize){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_read.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.find(query).sort(orderBy).limit(batchSize).toArray();
  }
 
  public int reomve(String collectionName,BasicDBObject o){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_write.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.remove(o).getN();
  }
 
  public int edit(String collectionName,BasicDBObject query,BasicDBObject update){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo_write.getDB(dataBaseName);
    DBCollection dbc = db.getCollection(collectionName);
    return dbc.update(query, update).getN();
    //return dbc.updateMulti(query, update).getN();
  }
 
  public int edit(String cmd){
//   DB db = MongoManager.getDB(dataBaseName);
    DB db = mongo.getDB(dataBaseName);
    CommandResult cmdResult = db.command(cmd);
    if(cmdResult.ok())
    {
      return 1;
    }
    return 0;
  }
 
// public DBCollection get(String collectionName){
////    DB db = MongoManager.getDB(dataBaseName);
//   DB db = mongo.getDB(dataBaseName);
//   return db.getCollection(collectionName);
// }
  public void setMongo(Mongo mongo) {
    this.mongo = mongo;
  }
  public void setMongo_read(Mongo mongo_read) {
    this.mongo_read = mongo_read;
  }
  public void setMongo_write(Mongo mongo_write) {
    this.mongo_write = mongo_write;
  }
 
 
 
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

延伸 · 阅读

精彩推荐
  • MongoDBMongoDB的索引

    MongoDB的索引

    数据库中的索引就是用来提高查询操作的性能,但是会影响插入、更新和删除的效率,因为数据库不仅要执行这些操作,还要负责索引的更新 ...

    MongoDB教程网2532020-05-12
  • MongoDBmongodb数据库基础知识之连表查询

    mongodb数据库基础知识之连表查询

    这篇文章主要给大家介绍了关于mongodb数据库基础知识之连表查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用mongodb具有一定的参...

    ZJW02155642020-05-22
  • MongoDBWindows下MongoDB配置用户权限实例

    Windows下MongoDB配置用户权限实例

    这篇文章主要介绍了Windows下MongoDB配置用户权限实例,本文实现需要输入用户名、密码才可以访问MongoDB数据库,需要的朋友可以参考下 ...

    MongoDB教程网3082020-04-29
  • MongoDBMongoDB多条件模糊查询示例代码

    MongoDB多条件模糊查询示例代码

    这篇文章主要给大家介绍了关于MongoDB多条件模糊查询的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用MongoDB具有一定的参考学习价值...

    浅夏晴空5902020-05-25
  • MongoDBMongoDB系列教程(五):mongo语法和mysql语法对比学习

    MongoDB系列教程(五):mongo语法和mysql语法对比学习

    这篇文章主要介绍了MongoDB系列教程(五):mongo语法和mysql语法对比学习,本文对熟悉Mysql数据库的同学来说帮助很大,用对比的方式可以快速学习到MongoDB的命...

    MongoDB教程网3252020-05-01
  • MongoDBMongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    MongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    这篇文章主要给大家介绍了关于MongoDB查询之高级操作(多条件查询、正则匹配查询等)的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者...

    w田翔3872020-12-19
  • MongoDB在mac系统下安装与配置mongoDB数据库

    在mac系统下安装与配置mongoDB数据库

    这篇文章主要介绍了在mac系统下安装与配置mongoDB数据库的操作步骤,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪...

    CXYhh1219312021-11-14
  • MongoDBMongodb索引的优化

    Mongodb索引的优化

    MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。接下来通过本文给大家介绍Mongodb索引的优化,本文介绍的非常详细,具有参考借鉴价值,感...

    MRR3252020-05-05