Class: Circuitbox::MemoryStore
- Inherits:
-
Object
- Object
- Circuitbox::MemoryStore
- Includes:
- TimeHelper::Monotonic
- Defined in:
- lib/circuitbox/memory_store.rb,
lib/circuitbox/memory_store/container.rb
Defined Under Namespace
Classes: Container
Instance Method Summary collapse
- #delete(key) ⇒ Object
- #increment(key, amount = 1, opts = {}) ⇒ Object
-
#initialize(compaction_frequency: 60) ⇒ MemoryStore
constructor
A new instance of MemoryStore.
- #key?(key) ⇒ Boolean
- #load(key, _opts = {}) ⇒ Object
- #store(key, value, opts = {}) ⇒ Object
- #values_at(*keys, **_opts) ⇒ Object
Methods included from TimeHelper::Monotonic
Constructor Details
#initialize(compaction_frequency: 60) ⇒ MemoryStore
Returns a new instance of MemoryStore.
10 11 12 13 14 15 |
# File 'lib/circuitbox/memory_store.rb', line 10 def initialize(compaction_frequency: 60) @store = {} @mutex = Mutex.new @compaction_frequency = compaction_frequency @compact_after = current_second + compaction_frequency end |
Instance Method Details
#delete(key) ⇒ Object
57 58 59 |
# File 'lib/circuitbox/memory_store.rb', line 57 def delete(key) @mutex.synchronize { @store.delete(key) } end |
#increment(key, amount = 1, opts = {}) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/circuitbox/memory_store.rb', line 24 def increment(key, amount = 1, opts = {}) seconds_to_expire = opts.fetch(:expires, 0) @mutex.synchronize do existing_container = fetch_container(key) # reusing the existing container is a small optimization # to reduce the amount of objects created if existing_container existing_container.expires_after(seconds_to_expire) existing_container.value += amount else @store[key] = Container.new(value: amount, expiry: seconds_to_expire) amount end end end |
#key?(key) ⇒ Boolean
53 54 55 |
# File 'lib/circuitbox/memory_store.rb', line 53 def key?(key) @mutex.synchronize { !fetch_container(key).nil? } end |
#load(key, _opts = {}) ⇒ Object
42 43 44 |
# File 'lib/circuitbox/memory_store.rb', line 42 def load(key, _opts = {}) @mutex.synchronize { fetch_container(key)&.value } end |
#store(key, value, opts = {}) ⇒ Object
17 18 19 20 21 22 |
# File 'lib/circuitbox/memory_store.rb', line 17 def store(key, value, opts = {}) @mutex.synchronize do @store[key] = Container.new(value: value, expiry: opts.fetch(:expires, 0)) value end end |
#values_at(*keys, **_opts) ⇒ Object
46 47 48 49 50 51 |
# File 'lib/circuitbox/memory_store.rb', line 46 def values_at(*keys, **_opts) @mutex.synchronize do current_time = current_second keys.map! { |key| fetch_container(key, current_time)&.value } end end |