您的位置:首页 > 数据库 > Mongodb

spring配置mongodb连接副本集多个节点

2017-12-07 14:36 591 查看
mongodb版本3.4.x

1、配置副本集

先配置副本集,可参考我之前写的文章:http://blog.csdn.net/fuck487/article/details/78287362

注意:必须配置仲裁节点,本来我以为仲裁节点作用不大,后来发现如果没配置仲裁节点,即使代码配置了多节点连接,一旦主节点关闭了,程序不会正常切到备用节点。

后来又验证了下:

要么1个主节点,1个从节点,1个仲裁

要么1个主节点,2个从节点

就是共大于等于3个节点,主节点关闭了,子节点

才能正常切换

2、spring配置(带密码的)

<?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:p="http://www.springframework.org/schema/p"
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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd"> 
<!-- mongodb 版本3.4.7 -->
<!--mongodb credentials的配置形式是:用户名:密码@默认数据库  -->
<!-- <mongo:mongo-client id="mongoClient" host="${db.host}" port="${db.port}" credentials="${db.user}:${db.pwd}@${db.name}"></mongo:mongo-client> -->

<!-- replica-set 副本集连接 -->
<!-- replica-set格式:ip1:port,ip2:port -->
<mongo:mongo-client id="mongoClient" replica-set="${db.replica-set}" credentials="${db.user}:${db.pwd}@${db.name}">
<mongo:client-options
connections-per-host="100"
/>
</mongo:mongo-client>

<mongo:db-factory id="mongoDbFactory" dbname="${db.name}" mongo-ref="mongoClient"/>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>

</beans>


其中主要是通过 replica-set="${db.replica-set}"来配置副本集
 replica-set的格式为ip1:port1,ip2:port2

只需要添加主从节点,不需要添加仲裁节点

3、属性文件

#mongodb-config
db.port=40000
db.host=127.0.0.1
db.user=dev
db.pwd=123456
db.name=isdb
db.replica-set=127.0.0.1:40000,127.0.0.1:40001
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: