Method: Memcached#initialize

Defined in:
lib/memcached/memcached.rb

#initialize(servers = nil, opts = {}) ⇒ Memcached

Create a new Memcached instance. Accepts string or array of server strings, as well an an optional configuration hash.

Memcached.new('localhost', ...) # A single server
Memcached.new(['web001:11212', 'web002:11212'], ...) # Two servers with custom ports
Memcached.new(['web001:11211:2', 'web002:11211:8'], ...) # Two servers with default ports and explicit weights

Weights only affect Ketama hashing. If you use Ketama hashing and don’t specify a weight, the client will poll each server’s stats and use its size as the weight.

Valid option parameters are:

:prefix_key

A string to prepend to every key, for namespacing. Max length is 127. Defaults to the empty string.

:prefix_delimiter

A character to postpend to the prefix key. Defaults to the empty string.

:hash

The name of a hash function to use. Possible values are: :crc, :default, :fnv1_32, :fnv1_64, :fnv1a_32, :fnv1a_64, :hsieh, :md5, and :murmur. :fnv1_32 is fast and well known, and is the default. Use :md5 for compatibility with other ketama clients.

:distribution

Either :modula, :consistent_ketama, :consistent_wheel, or :ketama. Defaults to :ketama.

:server_failure_limit

How many consecutive failures to allow before marking a host as dead. Has no effect unless :retry_timeout is also set.

:retry_timeout

How long to wait until retrying a dead server. Has no effect unless :server_failure_limit is non-zero. Defaults to 30.

:auto_eject_hosts

Whether to temporarily eject dead hosts from the pool. Defaults to true. Note that in the event of an ejection, :auto_eject_hosts will remap the entire pool unless :distribution is set to :consistent.

:exception_retry_limit

How many times to retry before raising exceptions in :exceptions_to_retry. Defaults to 5.

:exceptions_to_retry

Which exceptions to retry. Defaults to ServerIsMarkedDead, ATimeoutOccurred, ConnectionBindFailure, ConnectionFailure, ConnectionSocketCreateFailure, Failure, MemoryAllocationFailure, ReadFailure, ServerError, SystemError, UnknownReadFailure, and WriteFailure.

:cache_lookups

Whether to cache hostname lookups for the life of the instance. Defaults to true.

:support_cas

Flag CAS support in the client. Accepts true or false. Defaults to false because it imposes a slight performance penalty. Note that your server must also support CAS or you will trigger ProtocolError exceptions.

:tcp_nodelay

Turns on the no-delay feature for connecting sockets. Accepts true or false. Performance may or may not change, depending on your system.

:no_block

Whether to use pipelining for writes. Accepts true or false.

:buffer_requests

Whether to use an internal write buffer. Accepts true or false. Calling get or closing the connection will force the buffer to flush. Note that :buffer_requests might not work well without :no_block also enabled.

:show_backtraces

Whether NotFound and NotStored exceptions should include backtraces. Generating backtraces is slow, so this is off by default. Turn it on to ease debugging.

:connect_timeout

How long to wait for a connection to a server. Defaults to 2 seconds. Set to 0 if you want to wait forever.

:timeout

How long to wait for a response from the server. Defaults to 0.25 seconds. Set to 0 if you want to wait forever.

:default_ttl

The ttl to use on set if no ttl is specified, in seconds. Defaults to one week. Set to 0 if you want things to never expire.

:default_weight

The weight to use if :ketama_weighted is true, but no weight is specified for a server.

:hash_with_prefix_key

Whether to include the prefix when calculating which server a key falls on. Defaults to true.

:use_udp

Use the UDP protocol to reduce connection overhead. Defaults to false.

:binary_protocol

Use the binary protocol to reduce query processing overhead. Defaults to false.

:sort_hosts

Whether to force the server list to stay sorted. This defeats consistent hashing and is rarely useful.

:verify_key

Validate keys before accepting them. Never disable this.

Please note that when :no_block => true, update methods do not raise on errors. For example, if you try to set an invalid key, it will appear to succeed. The actual setting of the key occurs after libmemcached has returned control to your program, so there is no way to backtrack and raise the exception.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/memcached/memcached.rb', line 99

def initialize(servers = nil, opts = {})
  @struct = Lib.memcached_create(nil)

  # Merge option defaults and discard meaningless keys
  @options = DEFAULTS.merge(opts)
  @options.delete_if { |k,v| not DEFAULTS.keys.include? k }
  @default_ttl = options[:default_ttl]

  if servers == nil || servers == []
    if ENV.key?("MEMCACHE_SERVERS")
      servers = ENV["MEMCACHE_SERVERS"].split(",").map do | s | s.strip end
    else
      servers = "127.0.0.1:11211"
    end
  end

  if options[:credentials] == nil && ENV.key?("MEMCACHE_USERNAME") && ENV.key?("MEMCACHE_PASSWORD")
    options[:credentials] = [ENV["MEMCACHE_USERNAME"], ENV["MEMCACHE_PASSWORD"]]
  end

  options[:binary_protocol] = true if options[:credentials] != nil

  # Force :buffer_requests to use :no_block
  # XXX Deleting the :no_block key should also work, but libmemcached doesn't seem to set it
  # consistently
  options[:no_block] = true if options[:buffer_requests]

  # Disallow weights without ketama
  options.delete(:ketama_weighted) if options[:distribution] != :consistent_ketama

  # Disallow :sort_hosts with consistent hashing
  if options[:sort_hosts] and options[:distribution] == :consistent
    raise ArgumentError, ":sort_hosts defeats :consistent hashing"
  end

  # Read timeouts
  options[:rcv_timeout] ||= options[:timeout] || 0
  options[:poll_timeout] ||= options[:timeout] || 0

  # Set the prefix key. Support the legacy name.
  set_prefix_key(options.delete(:prefix_key) || options.delete(:namespace))

  # Set the behaviors and credentials on the struct
  set_behaviors
  set_credentials

  # Freeze the hash
  options.freeze

  # Set the servers on the struct
  set_servers(servers)

  # Not found exceptions
  unless options[:show_backtraces]
    @not_found = NotFound.new
    @not_found.no_backtrace = true
    @not_stored = NotStored.new
    @not_stored.no_backtrace = true
  end
end