无论我们学习什么语言,能打出一个Hello World成为了我们的第一步。而今天这个例子,相当于是MongoDB Replica Sets搭建的Hello World。代码如下:

下面是在Replica Sets上做操作后调用getlasterror使写操作同步到至少3台机器后才返回。

db.runCommand( { getlasterror : 1 , w : 3 } )

开始搭建,启动三个mongod server:

mongod --replSet prod --port 27017 --dbpath /data/node1
mongod --replSet prod --port 27027 --dbpath /data/node2
mongod --replSet prod --port 27037 --dbpath /data/node3

进行其中一个mongod,完成相关的配置

replica_config = {_id: 'prod', members: [
                          {_id: 0, host: 'localhost:27017'},
                          {_id: 1, host: 'localhost:27027'},
                          {_id: 2, host: 'localhost:27037'}]}
#Now initiate the replica_config
rs.initiate(replica_config);

ruby客户端代码:

#!/usr/bin/env ruby
require 'mongo'
begin
  @connection = Mongo::Connection.multi([
                                       ['localhost',27017],
                                       ['localhost',27027],
                                       ['localhost',27037]])
  @collection = @connection.db("sales").collection("products")
  product = { "name" => "Refactoring",
              "code" => "023XX3",
              "type" => "book",
              "in_stock" => 100}
  @collection.insert(product)
  100.times do
    sleep 0.5
    begin
  	  product = @collection.find_one "code" => "023XX3"
  	  puts "Found Book: "+product["name"]
  	rescue Exception => e
    	puts e.message
    	next
  	end
  end
end

原文链接:《Replicas Sets In MongoDB

MongoDB专题:http://mongodb.bigdataunion.org

10-28 18:31