Sha256: eddb304036bd6aa4da46209dd1e728b68cfc95cedde374cb8c9be0a0c75db7a2

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

require 'dalli-elasticache'
require 'alephant/logger'

module Alephant
  module Broker
    module Cache

      class Client
        include Logger

        DEFAULT_TTL  = 2592000

        def initialize
          unless config_endpoint.nil?
            @@elasticache ||= ::Dalli::ElastiCache.new(config_endpoint, { :expires_in => ttl })
            @client = @@elasticache.client
          else
            logger.info('Broker::Cache::Client#initialize: No config endpoint, NullClient used')
            @client = NullClient.new
          end
        end

        def config_endpoint
          Broker.config['elasticache_config_endpoint']
        end

        def ttl
           Broker.config['elasticache_ttl'] || DEFAULT_TTL
        end

        def get(key, &block)
          begin
            result = @client.get(key)
            logger.info("Broker::Cache::Client#get key: #{key} - #{result ? 'hit' : 'miss'}")
            result ? result : set(key, block.call)
          rescue StandardError => e
            block.call if block_given?
          end
        end

        def set(key, value)
          value.tap { |o| @client.set(key, o) }
        end

      end

      class NullClient
        def get(key); end

        def set(key, value)
          value
        end
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
alephant-broker-1.0.2 lib/alephant/broker/cache.rb
alephant-broker-1.0.1 lib/alephant/broker/cache.rb