三里屯摇滚 发表于 2012-02-16 19:31

Redis实现MongoDB的getlasterror功能

Redis实现MongoDB的getlasterror功能







MongoDB有一个命令叫getlasterror,从名字上看它的作用好像是获取最近的一个error。但其实这是MongoDB的一种客户端阻塞的方式。官方的解释如下:

MongoDB does not wait for a response by default when writing to the database. Use the getLastError command to ensure that operations have succeeded.

MongoDB 在写操作时,默认不会等数据写完后才返回,你可以通过使用getLastError命令来保证你的写是成功的。

说白了,MongoDB的写是异步的,返回给客户端成功但其写并不一定成功,而且在多个数据结点进行replication的时候,更无法保证数据同步到其它结点上。getLastError就是为此而生的,你指定一个条件,然后这个函数会一直阻塞到服务端告知这个条件满足了才会返回值。(当然,为了防止死等,这个函数还有一个超时参数),例子:

db.runCommand( { getlasterror : 1 , w : 2 } )上面命令表示等写操作被写到两个结点再返回成功。

这一功能使得数据安全性的保证更加灵活。

而最近有朋友在Redis上也实现了这一功能,实现的方式不是修改Redis源码,而是使用现有的功能拼得出,具体过程如下:

1. Client SUBSCRIBEs toKEY on *slave*
2. Client writes KEY (e.g. set foo bar) to master
3. Client publishes KEY to master

由于Redis的单线程写操作,下面两个操作会被顺序执行

4. Master will replicate KEY to slave
5 Master will propogate *PUBLISH KEY* to slave

最后,在Master同步完数据后,客户端会收到SUBSCRIBE的消息:
6. Gets KEY event on SUBSCRIBE!

来源:http://goo.gl/7zDPb

小鬼萌萌控 发表于 2012-02-17 22:32

谢谢分享
页: [1]
查看完整版本: Redis实现MongoDB的getlasterror功能