暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

mongodb中的读偏好让程序运行更快

437

昨天写的《mongodb是如何保障数据真正写入的》提到了Write Concern,本文要说的不是与之对应的 Read Concern,而是Read Preference(读偏好)。

默认情况下,mongodb的所有读操作都在primary副本集中,但读操作也可以来源于secondary副本集,原因一方面是为了分担读的压力,另外就是一定程度上可以提高读的可用性。

至于选择那种Read Preference,完全取决于开发者,前提就是了解每种Read Preference是否符合你的需求,做一定的取舍。

有几个注意点:

  • 对于secondary副本集来说,同步primary 的oplog是异步的,必然会有延迟,如果确实要从secondary读,一定要知晓这种情况的存在。

  • Read Preference不会影响数据的可见性,比如write操作的ack还没有返回,但某个secondary已经写入了,如果某个读正好访问到对应的secondary,那么就能看到最新的数据。

  • read preference不会影响causal consistency,这个暂且不说,The causal consistency guarantees provided by causally consistent sessions for read operations with “majority” read concern and write operations with “majority” write concern hold across all members of the MongoDB deployment.

Read preference由三部分组成:

  • preference mode

  • Read Preference maxStalenessSeconds.

  • a tag set(没用过)

preference mode有以下几种:

  • primary,默认的,所有的读都来自primary,如果primary挂了(会有这种情况),那么读服务就不能用了。

  • primaryPreferred,优先去primary读,但如果primary不可用,则读取secondary。

  • secondary,去secondary读,由于secondary一般情况下有多个,所以可用性还是不错的。

  • secondaryPreferred,优先去secondary读,如果所有的secondary都不可用,则去primary读。

  • nearest,选择网络延迟最小的一个副本集去读。

maxStalenessSeconds这个选项很有用,客户端会比较secondary副本集的同步延迟时间,如果大于maxStalenessSeconds,就会去选择一个延迟最小的副本集。

mongo shell调用:

db.users.find({}).readPref( "secondary",  [ { } ] )

php mongo调用:

$client = new MongoDB\Client("mongodb://localhost:27017", 
[
'readPreference' => 'secondaryPreferred',
]);
$collection = $client->test->users;
$cursor = $collection->find([]);

文章转载自虞大胆的叽叽喳喳,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论