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
---------------------
本文來自 不屑哥 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/fuck487/article/details/78741024?utm_source=copy