Last active
August 29, 2015 14:07
-
-
Save f440/1069f608966554b2e6fe to your computer and use it in GitHub Desktop.
redis-rb で watch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'redis' | |
require 'hiredis' | |
# usage: | |
# 端末(1) : 更新し続ける | |
# watch -n 0.1 "echo incr r | redis-cli" | |
# 端末(2) : watch しつつ更新する | |
# ruby redis_watch.rb 1000000 | |
r = Redis.new(driver: :hiredis, timeout: 60) # デフォルトだと、5秒でタイムアウト | |
puts "challenge!" | |
r.watch 'x' do | |
x = r.get 'x' | |
res = r.multi do |m| | |
(1..ARGV[0].to_i).each do |i| | |
m.incr 'x' | |
end | |
end | |
# 途中で書き換えられると res は nil になる | |
# うまくいっていれば、multi の結果が res に入っている | |
p res | |
end | |
# リトライする場合 | |
loop do | |
r = Redis.new(driver: :hiredis, timeout: 60) | |
puts "challenge!" | |
res = nil | |
r.watch 'x' do | |
x = r.get 'x' | |
res = r.multi do |m| | |
(1..ARGV[0].to_i).each do |i| | |
m.incr 'x' | |
end | |
end | |
end | |
# 途中で書き換えられると res は nil のまま | |
# watch のブロックの中から呼ぶと、break はブロックから抜けるだけで | |
# loop から抜けられない | |
if res | |
p res | |
break | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment