class ZkCache
Public Class Methods
cache_exists?()
click to toggle source
# File lib/caches/zk_cache.rb, line 23 def cache_exists? # @@client.read('test') # rescue Exception => error # @@client = nil Net::HTTP.get(URI("http://#{@@config['host']}")) rescue Errno::ECONNREFUSED => error puts "Could not connect to Zookeeper: #{error.message}" @@client = nil rescue EOFError => error # do nothing end
client()
click to toggle source
# File lib/caches/zk_cache.rb, line 10 def client @@client end
decode_data(data)
click to toggle source
# File lib/caches/zk_cache.rb, line 82 def decode_data(data) ActiveSupport::JSON.decode(data) rescue => error data end
delete(key, options = {})
click to toggle source
# File lib/caches/zk_cache.rb, line 73 def delete(key, options = {}) return unless client key = process_key(key) deleted = read(key) client.delete(path: key) deleted end
expires?(data)
click to toggle source
# File lib/caches/zk_cache.rb, line 88 def expires?(data) return true if (data.nil? || !data.is_a?(Hash)) data = data.with_indifferent_access return DateTime.parse(data[:last_read]).to_i + data[:expires_in].to_i < Time.now.to_i end
initialize()
click to toggle source
# File lib/caches/zk_cache.rb, line 14 def initialize @@config ||= ConfigService.load_config('zookeeper.yml')[ConfigService.environment] @@client ||= Zookeeper.new(@@config['host']) cache_exists? rescue Exception => error puts("ZkCache.initialize error: #{error.message}") @@client = nil end
read(key, options = {})
click to toggle source
Cache API, mimics ActiveSupport::Cache::Store api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html
# File lib/caches/zk_cache.rb, line 37 def read(key, options = {}) return unless client key = process_key(key) result = client.get(path: key)[:data] result = decode_data(result) return result unless result.is_a?(Hash) sym_data = result.with_indifferent_access return sym_data unless sym_data[:zk_cache_data].present? sym_data = sym_data[:zk_cache_data] return nil if expires?(sym_data) sym_data[:value] end
write(key, value, options = {})
click to toggle source
# File lib/caches/zk_cache.rb, line 55 def write(key, value, options = {}) return unless client key = process_key(key) init_key(key, nil) written_value = value if options[:expires_in].to_i > 0 written_value = { zk_cache_data: { value: value, expires_in: (options[:expires_in].to_i), last_read: Time.now } }.to_json end client.set(path: key, data: written_value) end
Private Class Methods
init_key(key, data)
click to toggle source
# File lib/caches/zk_cache.rb, line 96 def init_key(key, data) process_key(key) if @@client.get(path: key)[:data].nil? SdkLogger.logger.info("Create zookeeper path #{key} ...") @@client.create(path: key, data: data) end end
process_key(key)
click to toggle source
# File lib/caches/zk_cache.rb, line 105 def process_key(key) key = "/#{key}" unless key.starts_with?('/') key end