Method: MemCache#get_multi
- Defined in:
- lib/memcache.rb
#get_multi(*keys) ⇒ Object
Retrieves multiple values from memcached in parallel, if possible.
The memcached protocol supports the ability to retrieve multiple keys in a single request. Pass in an array of keys to this method and it will:
-
map the key to the appropriate memcached server
-
send a single request to each server that has one or more key values
Returns a hash of values.
cache["a"] = 1
cache["b"] = 2
cache.get_multi "a", "b" # => { "a" => 1, "b" => 2 }
Note that get_multi assumes the values are marshalled. You can pass in :raw => true to bypass value marshalling.
cache.get_multi('a', 'b', ..., :raw => true)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/memcache.rb', line 297 def get_multi(*keys) raise MemCacheError, 'No active servers' unless active? opts = keys.last.is_a?(Hash) ? keys.pop : {} keys.flatten! key_count = keys.length cache_keys = {} server_keys = Hash.new { |h,k| h[k] = [] } # map keys to servers keys.each do |key| server, cache_key = request_setup key cache_keys[cache_key] = key server_keys[server] << cache_key end results = {} raw = opts[:raw] || false server_keys.each do |server, keys_for_server| keys_for_server_str = keys_for_server.join ' ' begin values = cache_get_multi server, keys_for_server_str values.each do |key, value| results[cache_keys[key]] = raw ? value : Marshal.load(value) end rescue IndexError => e # Ignore this server and try the others logger.warn { "Unable to retrieve #{keys_for_server.size} elements from #{server.inspect}: #{e.}"} if logger end end return results rescue TypeError => err handle_error nil, err end |