Class: XRuntime::DataSet
- Inherits:
-
Object
- Object
- XRuntime::DataSet
- Defined in:
- lib/x_runtime/data_set.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
Returns the value of attribute data.
Instance Method Summary collapse
- #add(member, score) ⇒ Object
- #del(member) ⇒ Object
-
#initialize(key, script, count, expire) ⇒ DataSet
constructor
A new instance of DataSet.
-
#latest(opts = {}) ⇒ Object
=> {:score => score, :count => count, :average => average}.
- #size ⇒ Object
Constructor Details
#initialize(key, script, count, expire) ⇒ DataSet
Returns a new instance of DataSet.
5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/x_runtime/data_set.rb', line 5 def initialize(key, script, count, expire) raise ArgumentError, "Script must not nil and be valid!" unless script @key = key @key_counter = "#{@key}::Counter" @key_amount = "#{@key}::Amount" @key_average = "#{@key}::Average" @script = script @count = count @expire = expire @expired_at = Time.now.to_i @data = [] end |
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
3 4 5 |
# File 'lib/x_runtime/data_set.rb', line 3 def data @data end |
Instance Method Details
#add(member, score) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/x_runtime/data_set.rb', line 47 def add(member, score) @data.push([member, score]) # 如果@data数据达到一定数量,则一起插入redis # 如果上一次写入Redis和这次请求相差时间大于@expire,则在本次请求时也将缓存数据写入Redis if (@data.size >= @count) or (Time.now.to_i - @expired_at >= @expire) @expired_at = Time.now.to_i @script.redis.multi do while (data = @data.pop) do @script.evalsha(:add, [@key], [data[0], data[1]]) end end end end |
#del(member) ⇒ Object
61 62 63 |
# File 'lib/x_runtime/data_set.rb', line 61 def del(member) @script.evalsha(:del, [@key], [member]) end |
#latest(opts = {}) ⇒ Object
=> {:score => score, :count => count, :average => average}
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/x_runtime/data_set.rb', line 19 def latest(opts = {}) opts.delete_if{|k,v| v == nil} opts = {:limit => 100, :offset => 0}.update(opts) data = {} key_average = @script.redis .zrevrangebyscore(@key_average, '+inf', '-inf', :limit => [opts[:offset], opts[:limit]], :withscores => true) .inject({}){|hash, array|hash[array[0]] = array[1]; hash} if key_average.size > 0 key_count = {} keys = key_average.keys @script.redis.hmget(@key_counter, *key_average.keys).each_with_index{|count, idx| key_count[keys[idx]] = count} key_average.keys.each do |key| data[key] = { :latest => @script.redis.zscore(@key, key), :count => key_count[key], :average => key_average[key] } end end data end |
#size ⇒ Object
43 44 45 |
# File 'lib/x_runtime/data_set.rb', line 43 def size @script.redis.zcard(@key) end |