Sha256: 8df11b09221f86207c217d5ac17c6c2782c041a323bf3b5fc2bc7bbd5d2b4a4a

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

require "dalli-elasticache"
require "alephant/logger"

module Alephant
  module Broker
    module Cache
      class Client
        include Logger

        DEFAULT_TTL = 2_592_000

        def initialize
          if config_endpoint.nil?
            logger.debug "Broker::Cache::Client#initialize: No config endpoint, NullClient used"
            logger.metric "NoConfigEndpoint"
            @client = NullClient.new
          else
            @elasticache ||= ::Dalli::ElastiCache.new(config_endpoint, :expires_in => ttl)
            @client ||= @elasticache.client
          end
        end

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

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

        private

        def config_endpoint
          Broker.config["elasticache_config_endpoint"]
        end

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

        def versioned(key)
          [key, cache_version].compact.join("_")
        end

        def cache_version
          Broker.config["elasticache_cache_version"]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
alephant-broker-3.14.0 lib/alephant/broker/cache/client.rb