Class: CRUDJT::LRUCache
- Inherits:
-
Object
- Object
- CRUDJT::LRUCache
- Defined in:
- lib/lru_cache.rb
Constant Summary collapse
- CACHE_CAPACITY =
40_000
Instance Method Summary collapse
- #delete(token) ⇒ Object
- #force_insert(token, hash) ⇒ Object
- #get(token) ⇒ Object
-
#initialize(read_func) ⇒ LRUCache
constructor
A new instance of LRUCache.
- #insert(key, value, ttl, silence_read) ⇒ Object
Constructor Details
#initialize(read_func) ⇒ LRUCache
Returns a new instance of LRUCache.
7 8 9 10 |
# File 'lib/lru_cache.rb', line 7 def initialize(read_func) @cache = LruRedux::ThreadSafeCache.new(CACHE_CAPACITY) @read_func = read_func end |
Instance Method Details
#delete(token) ⇒ Object
69 70 71 |
# File 'lib/lru_cache.rb', line 69 def delete(token) cache.delete(token) end |
#force_insert(token, hash) ⇒ Object
65 66 67 |
# File 'lib/lru_cache.rb', line 65 def force_insert(token, hash) cache[token] = hash end |
#get(token) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/lru_cache.rb', line 12 def get(token) cached_value = cache[token] if cached_value && cached_value[:data] cached_value[:data] = MessagePack.unpack(cached_value[:data]) cached_value['data'] = cached_value.delete(:data) end if cached_value output = {} if cached_value.dig('metadata', 'ttl') ttl = (cached_value['metadata']['ttl'].to_i - Time.now.to_i).ceil if ttl <= 0 cache.delete(token) return end output['metadata'] = {} output['metadata']['ttl'] = ttl end silence_read = cached_value.dig('metadata', 'silence_read') if silence_read silence_read = cached_value['metadata']['silence_read'] -= 1 output['metadata'] ||= {} output['metadata']['silence_read'] = silence_read cache.delete(token) if silence_read <= 0 end read_func.call(token) if silence_read output['data'] = cached_value['data'] return output end end |
#insert(key, value, ttl, silence_read) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/lru_cache.rb', line 49 def insert(key, value, ttl, silence_read) hash = { data: value } if ttl > 0 hash['metadata'] = {} hash['metadata']['ttl'] = (Time.now + ttl) end if silence_read > 0 hash['metadata'] ||= {} hash['metadata']['silence_read'] = silence_read end cache[key] = hash end |