class Hoodoo::TransientStore::Redis
Hoodoo::TransientStore
plugin supporting Redis. The redis-rb gem is used for server communication.
Public Class Methods
See Hoodoo::TransientStore::Base::new
for details.
Do not instantiate this class directly. Use Hoodoo::TransientStore::new
.
The redis-rb gem is used to talk to Redis and requires connection UIRs with a redis
protocol, such as redis://localhost:6379
.
TCP keep-alive is enabled for the server connection.
Hoodoo::TransientStore::Base::new
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 36 def initialize( storage_host_uri:, namespace: ) super # Pass all arguments through -> *not* 'super()' @client = connect_to_redis( storage_host_uri ) end
Public Instance Methods
See Hoodoo::TransientStore::Base#close
for details.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 71 def close @client.quit() end
See Hoodoo::TransientStore::Base#delete
for details.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 64 def delete( key: ) @client.del( namespaced_key( key ) ) true end
See Hoodoo::TransientStore::Base#get
for details.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 57 def get( key: ) result = @client.get( namespaced_key( key ) ) return result.nil? ? nil : ( JSON.parse( result ) rescue nil ) end
See Hoodoo::TransientStore::Base#set
for details.
The payload is encoded into JSON for storage and automatically decoded by get
; so callers don’t need to do marshalling to Strings themselves.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 46 def set( key:, payload:, maximum_lifespan: ) nk = namespaced_key( key ) @client.set( nk, JSON.fast_generate( payload ) ) @client.expire( nk, maximum_lifespan ) true end
Private Instance Methods
Connect to Redis
if possible and return the connected Redis
client instance, else raise an exception.
host
-
Connection URI, e.g.
localhost:11211
.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 89 def connect_to_redis( host ) exception = nil info = nil client = nil if Hoodoo::Services::Middleware.environment.test? && ( host.nil? || host.empty? ) return Hoodoo::TransientStore::Mocks::Redis.new end begin client = ::Redis.new( :url => host, :tcp_keepalive => 1 ) info = client.info( 'CPU' ) rescue => e exception = e end if info.nil? if exception.nil? raise "Hoodoo::TransientStore::Redis: Did not get back meaningful data from Redis at '#{ host }'" else raise "Hoodoo::TransientStore::Redis: Cannot connect to Redis at '#{ host }': #{ exception.to_s }" end else return client end end
Given a simple key to Redis
data (expressed as a String), return a namespaced version by adding the configured namespace as a prefix.
# File lib/hoodoo/transient_store/transient_store/redis.rb, line 80 def namespaced_key( key ) @namespace + key end