Back to home page

Redis cross reference

 
 

    


0001 # redis-copy.rb - Copyright (C) 2009-2010 Salvatore Sanfilippo
0002 # BSD license, See the COPYING file for more information.
0003 #
0004 # Copy the whole dataset from one Redis instance to another one
0005 #
0006 # WARNING: currently hashes and sorted sets are not supported! This
0007 #          program should be updated.
0008 
0009 require
0010 require
0011 require
0012 
0013 def redisCopy(opts={})
0014     sha1=""
0015     src = Redis.new(:host => opts[:srchost], :port => opts[:srcport])
0016     dst = Redis.new(:host => opts[:dsthost], :port => opts[:dstport])
0017     puts "Loading key names..."
0018     keys = src.keys('*')
0019     puts "Copying #{keys.length} keys..."
0020     c = 0
0021     keys.each{|k|
0022         vtype = src.type?(k)
0023         ttl = src.ttl(k).to_i if vtype != "none"
0024 
0025         if vtype == "string"
0026             dst[k] = src[k]
0027         elsif vtype == "list"
0028             list = src.lrange(k,0,-1)
0029             if list.length == 0
0030                 # Empty list special case
0031                 dst.lpush(k,"")
0032                 dst.lpop(k)
0033             else
0034                 list.each{|ele|
0035                     dst.rpush(k,ele)
0036                 }
0037             end
0038         elsif vtype == "set"
0039             set = src.smembers(k)
0040             if set.length == 0
0041                 # Empty set special case
0042                 dst.sadd(k,"")
0043                 dst.srem(k,"")
0044             else
0045                 set.each{|ele|
0046                     dst.sadd(k,ele)
0047                 }
0048             end
0049         elsif vtype == "none"
0050             puts "WARNING: key '#{k}' was removed in the meanwhile."
0051         end
0052 
0053         # Handle keys with an expire time set
0054         if ttl != -1 and vtype != "none"
0055             dst.expire(k,ttl)
0056         end
0057 
0058         c = c+1
0059         if (c % 1000) == 0
0060             puts "#{c}/#{keys.length} completed"
0061         end
0062     }
0063     puts "DONE!"
0064 end
0065 
0066 if ARGV.length != 4
0067     puts "Usage: redis-copy.rb <srchost> <srcport> <dsthost> <dstport>"
0068     exit 1
0069 end
0070 puts "WARNING: it's up to you to FLUSHDB the destination host before to continue, press any key when ready."
0071 STDIN.gets
0072 srchost = ARGV[0]
0073 srcport = ARGV[1]
0074 dsthost = ARGV[2]
0075 dstport = ARGV[3]
0076 puts "Copying #{srchost}:#{srcport} into #{dsthost}:#{dstport}"
0077 redisCopy(:srchost => srchost, :srcport => srcport.to_i,
0078           :dsthost => dsthost, :dstport => dstport.to_i)