Class: Karafka::Web::Ui::Lib::TtlCache

Inherits:
Object
  • Object
show all
Includes:
Core::Helpers::Time
Defined in:
lib/karafka/web/ui/lib/ttl_cache.rb

Overview

Note:

It is thread-safe

Ttl Cache for caching things in-memory

Instance Method Summary collapse

Constructor Details

#initialize(ttl) ⇒ TtlCache

Returns a new instance of TtlCache.

Parameters:

  • ttl (Integer)

    time in ms how long should this cache keep data



14
15
16
17
18
19
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 14

def initialize(ttl)
  @ttl = ttl
  @times = {}
  @values = {}
  @mutex = Mutex.new
end

Instance Method Details

#clearObject

Clears the whole cache



60
61
62
63
64
65
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 60

def clear
  @mutex.synchronize do
    @times.clear
    @values.clear
  end
end

#fetch(key) ⇒ Object

Reads from the cache and if value not present, will run the block and store its result in the cache

Parameters:

  • key (String, Symbol)

    key for the cache read

Returns:

  • (Object)

    anything that was cached or yielded



49
50
51
52
53
54
55
56
57
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 49

def fetch(key)
  @mutex.synchronize do
    evict

    return @values[key] if @values.key?(key)

    @values[key] = yield
  end
end

#read(key) ⇒ Object

Reads data from the cache

Parameters:

  • key (String, Symbol)

    key for the cache read

Returns:

  • (Object)

    anything that was cached



25
26
27
28
29
30
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 25

def read(key)
  @mutex.synchronize do
    evict
    @values[key]
  end
end

#write(key, value) ⇒ Object

Writes to the cache

Parameters:

  • key (String, Symbol)

    key for the cache

  • value (Object)

    value we want to cache

Returns:

  • (Object)

    value we have written



37
38
39
40
41
42
# File 'lib/karafka/web/ui/lib/ttl_cache.rb', line 37

def write(key, value)
  @mutex.synchronize do
    @times[key] = monotonic_now + @ttl
    @values[key] = value
  end
end