在Linux上实现MongoDB的读写分离,通常需要以下几个步骤:
配置主从复制(Replication):
配置读偏好(Read Preference):
配置连接字符串:
以下是一个示例配置:
假设你有三个MongoDB服务器,分别是mongo1, mongo2, 和 mongo3。你可以使用以下命令初始化副本集:
mongo --host mongo1 --eval 'rs.initiate({
_id: "myReplicaSet",
members: [
{ _id: 0, host: "mongo1:27017" },
{ _id: 1, host: "mongo2:27017" },
{ _id: 2, host: "mongo3:27017" }
]
})'
在应用程序中,你可以设置读偏好为secondaryPreferred,这样读操作会优先从从节点读取:
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=myReplicaSet&readPreference=secondaryPreferred';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
await client.connect();
const database = client.db('mydatabase');
const collection = database.collection('mycollection');
// 执行读操作
const result = await collection.find({}).toArray();
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.error);
通过以上步骤,你可以在Linux上实现MongoDB的读写分离,提高系统的读取性能和可用性。