Skip to content

Instantly share code, notes, and snippets.

@iscander
Created December 2, 2009 15:04
Show Gist options
  • Save iscander/247258 to your computer and use it in GitHub Desktop.
Save iscander/247258 to your computer and use it in GitHub Desktop.
require 'redis'
require 'thread'
# Redis DataBase interface to save collected statistic
# new object apply any of the following parameters if needed:
# :host if you need to connect to an external host instead of the default 127.0.0.1
# :port if you need to use something other than Redis' default port of 6379
# :password if you configured Redis to require a password on connection
# :db if you want to select one of the multiple configured databases, other
# than the default of 0 (databases are identified by a zero-based index)
# :timeout if you want a different timeout for Redis communication than the
# default of 5 seconds
# :logger if you want the library to log activity as it works
##
# set_values() and inc_values() recieve Entry Objects array as params. Each Entry object
# has name,value and prefix attributes
# set_values() save value of database key to each Entry Object value with same "prefix+key" name
# inc_values() increment database values to a value with the same key of each Entry Object
# batch_command() build one-command-multiple-values request to Redis Database
class StatToRedisInterface
def initialize(params=Hash.new)
@db = Redis.new(params)
@semaphore = Mutex.new
end
def set_values(params=[])
@semaphore.synchronize {
batch_command(params){|commands,entry| commands[entry.prefix+entry.name] = entry.value}
}
end
def inc_values(params=[])
@semaphore.synchronize {
batch_command(params){|commands,entry| commands.incr( entry.prefix+entry.name, entry.value)}
}
end
private
def batch_command(params,&block)
@db.pipelined do |commands|
params.each do |entry|
yield(commands,entry)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment