|
Revision 326, 1.5 kB
(checked in by gethema..@gmail.com, 6 months ago)
|
check in new backgroundrb code
|
| Line | |
|---|
| 1 |
module BackgrounDRb |
|---|
| 2 |
class ResultStorage |
|---|
| 3 |
attr_accessor :cache,:worker_name,:worker_key,:storage_type |
|---|
| 4 |
def initialize(worker_name,worker_key,storage_type = nil) |
|---|
| 5 |
@worker_name = worker_name |
|---|
| 6 |
@worker_key = worker_key |
|---|
| 7 |
@mutex = Mutex.new |
|---|
| 8 |
@storage_type = storage_type |
|---|
| 9 |
@cache = (@storage_type == 'memcache') ? memcache_instance : {} |
|---|
| 10 |
end |
|---|
| 11 |
|
|---|
| 12 |
# Initialize Memcache for result or object caching |
|---|
| 13 |
def memcache_instance |
|---|
| 14 |
require 'memcache' |
|---|
| 15 |
memcache_options = { |
|---|
| 16 |
:c_threshold => 10_000, |
|---|
| 17 |
:compression => true, |
|---|
| 18 |
:debug => false, |
|---|
| 19 |
:namespace => 'backgroundrb_result_hash', |
|---|
| 20 |
:readonly => false, |
|---|
| 21 |
:urlencode => false |
|---|
| 22 |
} |
|---|
| 23 |
t_cache = MemCache.new(memcache_options) |
|---|
| 24 |
t_cache.servers = BDRB_CONFIG[:memcache].split(',') |
|---|
| 25 |
t_cache |
|---|
| 26 |
end |
|---|
| 27 |
|
|---|
| 28 |
# generate key based on worker_name and worker_key |
|---|
| 29 |
# for local cache, there is no need of unique key |
|---|
| 30 |
def gen_key key |
|---|
| 31 |
if storage_type == 'memcache' |
|---|
| 32 |
key = [worker_name,worker_key,key].compact.join('_') |
|---|
| 33 |
key |
|---|
| 34 |
else |
|---|
| 35 |
key |
|---|
| 36 |
end |
|---|
| 37 |
end |
|---|
| 38 |
|
|---|
| 39 |
# fetch object from cache |
|---|
| 40 |
def [] key |
|---|
| 41 |
@mutex.synchronize { @cache[gen_key(key)] } |
|---|
| 42 |
end |
|---|
| 43 |
|
|---|
| 44 |
def []= key,value |
|---|
| 45 |
@mutex.synchronize { @cache[gen_key(key)] = value } |
|---|
| 46 |
end |
|---|
| 47 |
|
|---|
| 48 |
def delete key |
|---|
| 49 |
@mutex.synchronize { @cache.delete(gen_key(key)) } |
|---|
| 50 |
end |
|---|
| 51 |
|
|---|
| 52 |
def shift key |
|---|
| 53 |
val = nil |
|---|
| 54 |
@mutex.synchronize do |
|---|
| 55 |
val = @cache[key] |
|---|
| 56 |
@cache.delete(key) |
|---|
| 57 |
end |
|---|
| 58 |
return val |
|---|
| 59 |
end |
|---|
| 60 |
end |
|---|
| 61 |
end |
|---|
| 62 |
|
|---|