Sha256: 28a8d1884442529089487f79822c8f16d6b78cda7d7db7aafcd52533a3a60b03

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

require 'remcached/const'
require 'remcached/packet'
require 'remcached/client'

module Memcached
  class << self
    ##
    # +servers+: either Array of host:port strings or Hash of
    # host:port => weight integers
    def servers=(servers)
      if defined?(@clients) && @clients
        while client = @clients.shift
          client.close
        end
      end

      @clients = servers.collect { |server|
        host, port = server.split(':')
        Client.connect host, (port ? port.to_i : 11211)
      }
    end
  
    def usable?
      usable_clients.length > 0
    end

    def usable_clients
      unless defined?(@clients) && @clients
        []
      else
        @clients.select { |client| client.connected? }
      end
    end

    def client_for_key(key)
      usable_clients_ = usable_clients
      if usable_clients_.empty?
        nil
      else
        h = hash_key(key) % usable_clients_.length
        usable_clients_[h]
      end
    end

    def hash_key(key)
      hashed = 0
      i = 0
      key.each_byte do |b|
        j = key.length - i - 1 % 4
        hashed ^= b << (j * 8)
        i += 1
      end
      hashed
    end

    def operation(op, contents, &callback)
      client = client_for_key(contents[:key])
      if client
        client.send(op, contents, &callback)
      elsif callback
        callback.call :status => Errors::DISCONNECTED
      end
    end


    ##
    # Memcached operations
    ##

    def add(contents, &callback)
      operation :add, contents, &callback
    end
    def get(contents, &callback)
      operation :get, contents, &callback
    end
    def set(contents, &callback)
      operation :set, contents, &callback
    end
    def delete(contents, &callback)
      operation :delete, contents, &callback
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
astro-remcached-0.2.1 lib/remcached.rb