redis主从复制实验,使用ruby

时间:2022-03-14 08:47:09

redis相比memcached不仅多了数据持久化的部分,对多种数据结构的支持和主从复制的支持也更好了。

在这个实验中我增加了2个redis slave,即1个master(6379端口),2个slave(6389和6399端口),同样的数据备份3次。

2个slave的配置文件redis_slave1.conf, redis_slave2.conf的部分配置

# redis_slave1.conf
port 6389
slaveof localhost 6379
slave-read-only yes

# redis_slave2.conf
port 6399
slaveof localhost 6379
slave-read-only no

事后发现slave-read-only是个很鸡肋的选项,基本不是很有用。

然后用ruby写一段程序写一个字符串进去,当然是写到master的redis上。

 1 # 20140202, redis_test_master.rb
 2 
 3 require 'rubygems'
 4 require 'redis'
 5 
 6 redis=Redis.new(:host => "localhost", :port => 6379)
 7 
 8 puts ">>>>>>>>>>TEST REDIS STRING>>>>>>>>>>"
 9 redis.set:"str1","1234567890"
10 p redis.get:"str1"
11 puts "TEST " + (redis.type:"str1") + " END"
12 # redis.del:"str1"

输出是

>>>>>>>>>>TEST REDIS STRING>>>>>>>>>>
"1234567890"
TEST string END

然后再写一段ruby从slave1上读出来,

 1 # 20140202, redis_test_slave1.rb
 2 
 3 require 'rubygems'
 4 require 'redis'
 5 
 6 redis=Redis.new(:host => "localhost", :port => 6389)
 7 
 8 puts ">>>>>>>>>>TEST REDIS STRING>>>>>>>>>>"
 9 p redis.get:"str1"
10 puts "TEST " + (redis.type:"str1") + " END"

输出和master的那段程序一样,因为slave2上设置了可写,所以可以对slave2进行写操作,

 1 # 20140202, redis_test_slave2.rb
 2 
 3 require 'rubygems'
 4 require 'redis'
 5 
 6 redis=Redis.new(:host => "localhost", :port => 6399)
 7 
 8 puts ">>>>>>>>>>TEST REDIS STRING>>>>>>>>>>"
 9 p redis.get:"str1"
10 redis.set:"str1","12345"
11 p redis.get:"str1"
12 puts "TEST " + (redis.type:"str1") + " END"
13 # redis.del:"str1"

输出是

>>>>>>>>>>TEST REDIS STRING>>>>>>>>>>
"1234567890"
"12345"
TEST string END

如果尝试对没有设置slave可写的redis slave做写的动作,当然会报错,我的程序ruby报错如下

/var/lib/gems/1.9.1/gems/redis-3.0.7/lib/redis/client.rb:97:in `call': READONLY You can't write against a read only slave. (Redis::CommandError)
    from /var/lib/gems/1.9.1/gems/redis-3.0.7/lib/redis.rb:676:in `block in set'
    from /var/lib/gems/1.9.1/gems/redis-3.0.7/lib/redis.rb:37:in `block in synchronize'
    from /usr/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
    from /var/lib/gems/1.9.1/gems/redis-3.0.7/lib/redis.rb:37:in `synchronize'
    from /var/lib/gems/1.9.1/gems/redis-3.0.7/lib/redis.rb:672:in `set'
    from /home/arnes/project/ruby1/rb4/redis_test_slave2.rb:10:in `<main>'
[Finished in 0.1s with exit code 1]

如果是用redis-cli做这个实验,尝试写redis slave会报错如下

(error) READONLY You can't write against a read only slave.

那是不是只要用redis的话,就尽量打开slave可写选项呢?我认为,这个选项尽量不要打开,事实上,默认的redis.conf也是没有打开这个选项。原因是,即使打开了这个选项,向redis slave中写了数据,写入的数据也不会同步到master。所以,redis支持的是master-slave结构,而不是master-master这种双活结构。当下一次,master上的数据又有所修改之后,这个数据又会同步到slave上,slave上临时写入的数据就会被新的值覆盖。