Class: CloudConfig::Cache::Redis

Inherits:
Object
  • Object
show all
Defined in:
lib/cloud-config/cache/redis.rb

Overview

A simple class for storing key-value data in Redis.

Examples:

cache = CloudConfig::Cache::Redis.new(url:)
cache.set(:key_to_expire, :key_value, expire_in: 5)

cache.get(:key_to_expire) #=> :key_value

sleep 5

cache.get(:key_to_expire) #=> nil

Constant Summary collapse

DEFAULT_EXPIRE =

Default time to expire keys (seconds)

60 * 60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Redis

Returns a new instance of Redis.



24
25
26
# File 'lib/cloud-config/cache/redis.rb', line 24

def initialize(params = {})
  @client = ::Redis.new(params)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



22
23
24
# File 'lib/cloud-config/cache/redis.rb', line 22

def client
  @client
end

#Redis client(client) ⇒ Redis (readonly)

Returns:



22
# File 'lib/cloud-config/cache/redis.rb', line 22

attr_reader :client

Instance Method Details

#delete(key) ⇒ Object

Delete the key from the cache

Parameters:

  • key (String, Symbol)

    Key to delete



59
60
61
# File 'lib/cloud-config/cache/redis.rb', line 59

def delete(key)
  client.del(key)
end

#get(key) ⇒ Object

Fetch the key from the cache

Parameters:

  • key (String, Symbol)

    Key to check

Returns:

  • (Object)

    Value of key



42
43
44
# File 'lib/cloud-config/cache/redis.rb', line 42

def get(key)
  client.get(key)
end

#key?(key) ⇒ Boolean

Check whether the key exists in the cache. Expired keys will return false.

Parameters:

  • key (String, Symbol)

    Key to check

Returns:

  • (Boolean)

    Whether key exists



33
34
35
# File 'lib/cloud-config/cache/redis.rb', line 33

def key?(key)
  client.exists(key) == 1
end

#set(key, value, options = {}) ⇒ Object

Set the value of the key in the cache. Optionally set an expiry of the key, otherwise a default expiry of DEFAULT_EXPIRE will be set.

Parameters:

  • key (String, Symbol)

    Key to set

  • value (Object)

    Value of the key

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :expire_in (Hash)

    Time in seconds until key expires



52
53
54
# File 'lib/cloud-config/cache/redis.rb', line 52

def set(key, value, options = {})
  client.set(key, value, ex: options[:expire_in] || DEFAULT_EXPIRE)
end