Class: MemCache
- Inherits:
-
Object
- Object
- MemCache
- Defined in:
- lib/memcache.rb
Overview
A Ruby client library for memcached.
This is intended to provide access to basic memcached functionality. It does not attempt to be complete implementation of the entire API, but it is approaching a complete implementation.
Defined Under Namespace
Classes: MemCacheError, Server
Constant Summary collapse
- VERSION =
The version of MemCache you are using.
'1.5.0.1'- DEFAULT_OPTIONS =
Default options for the cache object.
{ :namespace => nil, :readonly => false, :multithread => false, }
- DEFAULT_PORT =
Default memcached port.
11211- DEFAULT_WEIGHT =
Default memcached server weight.
1
Instance Attribute Summary collapse
-
#multithread ⇒ Object
readonly
The multithread setting for this instance.
-
#namespace ⇒ Object
readonly
The namespace for this instance.
-
#request_timeout ⇒ Object
The amount of time to wait for a response from a memcached server.
-
#servers ⇒ Object
The servers this client talks to.
Instance Method Summary collapse
-
#[]=(key, value) ⇒ Object
Shortcut to save a value in the cache.
-
#active? ⇒ Boolean
Returns whether there is at least one active server for the object.
-
#add(key, value, expiry = 0, raw = false) ⇒ Object
Add
keyto the cache with valuevaluethat expires inexpiryseconds, but only ifkeydoes not already exist in the cache. -
#cache_decr(server, cache_key, amount) ⇒ Object
Performs a raw decr for
cache_keyfromserver. -
#cache_get(server, cache_key) ⇒ Object
Fetches the raw data for
cache_keyfromserver. -
#cache_get_multi(server, cache_keys) ⇒ Object
Fetches
cache_keysfromserverusing a multi-get. -
#cache_incr(server, cache_key, amount) ⇒ Object
Performs a raw incr for
cache_keyfromserver. -
#decr(key, amount = 1) ⇒ Object
Decrements the value for
keybyamountand returns the new value. -
#delete(key, expiry = 0) ⇒ Object
Removes
keyfrom the cache inexpiryseconds. -
#flush_all ⇒ Object
Flush the cache from all memcache servers.
-
#get(key, raw = false) ⇒ Object
(also: #[])
Retrieves
keyfrom memcache. -
#get_multi(*keys) ⇒ Object
Retrieves multiple values from memcached in parallel, if possible.
-
#get_server_for_key(key) ⇒ Object
Pick a server to handle the request based on a hash of the key.
-
#handle_error(server, error) ⇒ Object
Handles
errorfromserver. -
#hash_for(key) ⇒ Object
Returns an interoperable hash value for
key. -
#incr(key, amount = 1) ⇒ Object
Increments the value for
keybyamountand returns the new value. -
#initialize(*args) ⇒ MemCache
constructor
Accepts a list of
serversand a list ofopts. -
#inspect ⇒ Object
Returns a string representation of the cache object.
-
#make_cache_key(key) ⇒ Object
Create a key for the cache, incorporating the namespace qualifier if requested.
-
#readonly? ⇒ Boolean
Returns whether or not the cache object was created read only.
-
#request_setup(key) ⇒ Object
Performs setup for making a request with
keyfrom memcached. -
#reset ⇒ Object
Reset the connection to all memcache servers.
-
#set(key, value, expiry = 0, raw = false) ⇒ Object
Add
keyto the cache with valuevaluethat expires inexpiryseconds. -
#stats ⇒ Object
Returns statistics for each memcached server.
- #with_server(key) ⇒ Object
-
#with_socket_management(server, &block) ⇒ Object
Gets or creates a socket connected to the given server, and yields it to the block.
Constructor Details
#initialize(*args) ⇒ MemCache
Accepts a list of servers and a list of opts. servers may be omitted. See servers= for acceptable server list arguments.
Valid options for opts are:
[:namespace] Prepends this value to all keys added or retrieved.
[:readonly] Raises an exeception on cache writes when true.
[:multithread] Wraps cache access in a Mutex for thread safety.
Other options are ignored.
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 |
# File 'lib/memcache.rb', line 108 def initialize(*args) servers = [] opts = {} case args.length when 0 then # NOP when 1 then arg = args.shift case arg when Hash then opts = arg when Array then servers = arg when String then servers = [arg] else raise ArgumentError, 'first argument must be Array, Hash or String' end when 2 then servers, opts = args else raise ArgumentError, "wrong number of arguments (#{args.length} for 2)" end opts = DEFAULT_OPTIONS.merge opts @namespace = opts[:namespace] @readonly = opts[:readonly] @multithread = opts[:multithread] @mutex = Mutex.new if @multithread @buckets = [] self.servers = servers end |
Instance Attribute Details
#multithread ⇒ Object (readonly)
The multithread setting for this instance
89 90 91 |
# File 'lib/memcache.rb', line 89 def multithread @multithread end |
#namespace ⇒ Object (readonly)
The namespace for this instance
84 85 86 |
# File 'lib/memcache.rb', line 84 def namespace @namespace end |
#request_timeout ⇒ Object
The amount of time to wait for a response from a memcached server. If a response is not completed within this time, the connection to the server will be closed and an error will be raised.
79 80 81 |
# File 'lib/memcache.rb', line 79 def request_timeout @request_timeout end |
#servers ⇒ Object
The servers this client talks to. Play at your own peril.
94 95 96 |
# File 'lib/memcache.rb', line 94 def servers @servers end |
Instance Method Details
#[]=(key, value) ⇒ Object
Shortcut to save a value in the cache. This method does not set an expiration on the entry. Use set to specify an explicit expiry.
450 451 452 |
# File 'lib/memcache.rb', line 450 def []=(key, value) set key, value end |
#active? ⇒ Boolean
Returns whether there is at least one active server for the object.
148 149 150 |
# File 'lib/memcache.rb', line 148 def active? not @servers.empty? end |
#add(key, value, expiry = 0, raw = false) ⇒ Object
Add key to the cache with value value that expires in expiry seconds, but only if key does not already exist in the cache. If raw is true, value will not be Marshalled.
Readers should call this method in the event of a cache miss, not MemCache#set or MemCache#[]=.
317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/memcache.rb', line 317 def add(key, value, expiry = 0, raw = false) raise MemCacheError, "Update of readonly cache" if @readonly with_server(key) do |server, cache_key| value = Marshal.dump value unless raw command = "add #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" with_socket_management(server) do |socket| socket.write command socket.gets end end end |
#cache_decr(server, cache_key, amount) ⇒ Object
Performs a raw decr for cache_key from server. Returns nil if not found.
501 502 503 504 505 506 507 508 |
# File 'lib/memcache.rb', line 501 def cache_decr(server, cache_key, amount) with_socket_management(server) do |socket| socket.write "decr #{cache_key} #{amount}\r\n" text = socket.gets return nil if text == "NOT_FOUND\r\n" return text.to_i end end |
#cache_get(server, cache_key) ⇒ Object
Fetches the raw data for cache_key from server. Returns nil on cache miss.
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 |
# File 'lib/memcache.rb', line 514 def cache_get(server, cache_key) with_socket_management(server) do |socket| socket.write "get #{cache_key}\r\n" keyline = socket.gets # "VALUE <key> <flags> <bytes>\r\n" if keyline.nil? then server.close raise MemCacheError, "lost connection to #{server.host}:#{server.port}" # TODO: retry here too end return nil if keyline == "END\r\n" unless keyline =~ /(\d+)\r/ then server.close raise MemCacheError, "unexpected response #{keyline.inspect}" end value = socket.read $1.to_i socket.read 2 # "\r\n" socket.gets # "END\r\n" return value end end |
#cache_get_multi(server, cache_keys) ⇒ Object
Fetches cache_keys from server using a multi-get.
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/memcache.rb', line 540 def cache_get_multi(server, cache_keys) with_socket_management(server) do |socket| values = {} socket.write "get #{cache_keys}\r\n" while keyline = socket.gets do return values if keyline == "END\r\n" unless keyline =~ /^VALUE (.+) (.+) (.+)/ then server.close raise MemCacheError, "unexpected response #{keyline.inspect}" end key, data_length = $1, $3 values[$1] = socket.read data_length.to_i socket.read(2) # "\r\n" end server.close raise MemCacheError, "lost connection to #{server.host}:#{server.port}" # TODO: retry here too end end |
#cache_incr(server, cache_key, amount) ⇒ Object
Performs a raw incr for cache_key from server. Returns nil if not found.
567 568 569 570 571 572 573 574 |
# File 'lib/memcache.rb', line 567 def cache_incr(server, cache_key, amount) with_socket_management(server) do |socket| socket.write "incr #{cache_key} #{amount}\r\n" text = socket.gets return nil if text == "NOT_FOUND\r\n" return text.to_i end end |
#decr(key, amount = 1) ⇒ Object
Decrements the value for key by amount and returns the new value. key must already exist. If key is not an integer, it is assumed to be
-
keycan not be decremented below 0.
195 196 197 198 199 200 201 202 |
# File 'lib/memcache.rb', line 195 def decr(key, amount = 1) raise MemCacheError, "Update of readonly cache" if @readonly with_server(key) do |server, cache_key| cache_decr server, cache_key, amount end rescue TypeError => err handle_error server, err end |
#delete(key, expiry = 0) ⇒ Object
Removes key from the cache in expiry seconds.
333 334 335 336 337 338 339 340 341 |
# File 'lib/memcache.rb', line 333 def delete(key, expiry = 0) raise MemCacheError, "Update of readonly cache" if @readonly server, cache_key = request_setup key with_socket_management(server) do |socket| socket.write "delete #{cache_key} #{expiry}\r\n" socket.gets end end |
#flush_all ⇒ Object
Flush the cache from all memcache servers.
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/memcache.rb', line 346 def flush_all raise MemCacheError, 'No active servers' unless active? raise MemCacheError, "Update of readonly cache" if @readonly begin @mutex.lock if @multithread @servers.each do |server| with_socket_management(server) do |socket| socket.write "flush_all\r\n" result = socket.gets raise MemCacheError, $2.strip if result =~ /^(SERVER_)?ERROR(.*)/ end end ensure @mutex.unlock if @multithread end end |
#get(key, raw = false) ⇒ Object Also known as: []
Retrieves key from memcache. If raw is false, the value will be unmarshalled.
208 209 210 211 212 213 214 215 216 217 |
# File 'lib/memcache.rb', line 208 def get(key, raw = false) with_server(key) do |server, cache_key| value = cache_get server, cache_key return nil if value.nil? value = Marshal.load value unless raw return value end rescue TypeError => err handle_error server, err end |
#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 }
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/memcache.rb', line 235 def get_multi(*keys) raise MemCacheError, 'No active servers' unless active? 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 = {} server_keys.each do |server, keys| keys = keys.join ' ' values = cache_get_multi server, keys values.each do |key, value| results[cache_keys[key]] = Marshal.load value end end return results rescue TypeError => err handle_error server, err end |
#get_server_for_key(key) ⇒ Object
Pick a server to handle the request based on a hash of the key.
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
# File 'lib/memcache.rb', line 471 def get_server_for_key(key) raise ArgumentError, "illegal character in key #{key.inspect}" if key =~ /\s/ raise ArgumentError, "key too long #{key.inspect}" if key.length > 250 raise MemCacheError, "No servers available" if @servers.empty? return @servers.first if @servers.length == 1 hkey = hash_for key 20.times do |try| server = @buckets[hkey % @buckets.nitems] return server if server.alive? hkey += hash_for "#{try}#{key}" end raise MemCacheError, "No servers available" end |
#handle_error(server, error) ⇒ Object
Handles error from server.
624 625 626 627 628 629 630 |
# File 'lib/memcache.rb', line 624 def handle_error(server, error) raise error if error.is_a?(MemCacheError) server.close if server new_error = MemCacheError.new error. new_error.set_backtrace error.backtrace raise new_error end |
#hash_for(key) ⇒ Object
Returns an interoperable hash value for key. (I think, docs are sketchy for down servers).
493 494 495 |
# File 'lib/memcache.rb', line 493 def hash_for(key) (key.crc32_ITU_T >> 16) & 0x7fff end |
#incr(key, amount = 1) ⇒ Object
Increments the value for key by amount and returns the new value. key must already exist. If key is not an integer, it is assumed to be 0.
270 271 272 273 274 275 276 277 |
# File 'lib/memcache.rb', line 270 def incr(key, amount = 1) raise MemCacheError, "Update of readonly cache" if @readonly with_server(key) do |server, cache_key| cache_incr server, cache_key, amount end rescue TypeError => err handle_error server, err end |
#inspect ⇒ Object
Returns a string representation of the cache object.
140 141 142 143 |
# File 'lib/memcache.rb', line 140 def inspect "<MemCache: %d servers, %d buckets, ns: %p, ro: %p>" % [@servers.length, @buckets.length, @namespace, @readonly] end |
#make_cache_key(key) ⇒ Object
Create a key for the cache, incorporating the namespace qualifier if requested.
460 461 462 463 464 465 466 |
# File 'lib/memcache.rb', line 460 def make_cache_key(key) if namespace.nil? then key else "#{@namespace}:#{key}" end end |
#readonly? ⇒ Boolean
Returns whether or not the cache object was created read only.
155 156 157 |
# File 'lib/memcache.rb', line 155 def readonly? @readonly end |
#request_setup(key) ⇒ Object
Performs setup for making a request with key from memcached. Returns the server to fetch the key from and the complete key to use.
636 637 638 639 640 641 |
# File 'lib/memcache.rb', line 636 def request_setup(key) raise MemCacheError, 'No active servers' unless active? cache_key = make_cache_key key server = get_server_for_key cache_key return server, cache_key end |
#reset ⇒ Object
Reset the connection to all memcache servers. This should be called if there is a problem with a cache lookup that might have left the connection in a corrupted state.
368 369 370 |
# File 'lib/memcache.rb', line 368 def reset @servers.each { |server| server.close } end |
#set(key, value, expiry = 0, raw = false) ⇒ Object
Add key to the cache with value value that expires in expiry seconds. If raw is true, value will not be Marshalled.
Warning: Readers should not call this method in the event of a cache miss; see MemCache#add.
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# File 'lib/memcache.rb', line 286 def set(key, value, expiry = 0, raw = false) raise MemCacheError, "Update of readonly cache" if @readonly with_server(key) do |server, cache_key| value = Marshal.dump value unless raw command = "set #{cache_key} 0 #{expiry} #{value.to_s.size}\r\n#{value}\r\n" with_socket_management(server) do |socket| socket.write command result = socket.gets if result.nil? server.close raise MemCacheError, "lost connection to #{server.host}:#{server.port}" end if result =~ /^SERVER_ERROR (.*)/ server.close raise MemCacheError, $1.strip end end end end |
#stats ⇒ Object
Returns statistics for each memcached server. An explanation of the statistics can be found in the memcached docs:
code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt
Example:
>> pp CACHE.stats
{"localhost:11211"=>
{"bytes"=>4718,
"pid"=>20188,
"connection_structures"=>4,
"time"=>1162278121,
"pointer_size"=>32,
"limit_maxbytes"=>67108864,
"cmd_get"=>14532,
"version"=>"1.2.0",
"bytes_written"=>432583,
"cmd_set"=>32,
"get_misses"=>0,
"total_connections"=>19,
"curr_connections"=>3,
"curr_items"=>4,
"uptime"=>1557,
"get_hits"=>14532,
"total_items"=>32,
"rusage_system"=>0.313952,
"rusage_user"=>0.119981,
"bytes_read"=>190619}}
=> nil
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/memcache.rb', line 404 def stats raise MemCacheError, "No active servers" unless active? server_stats = {} @servers.each do |server| next unless server.alive? with_socket_management(server) do |socket| value = nil # TODO: why is this line here? socket.write "stats\r\n" stats = {} while line = socket.gets do break if line == "END\r\n" if line =~ /^STAT ([\w]+) ([\w\.\:]+)/ then name, value = $1, $2 stats[name] = case name when 'version' value when 'rusage_user', 'rusage_system' then seconds, microseconds = value.split(/:/, 2) microseconds ||= 0 Float(seconds) + (Float(microseconds) / 1_000_000) else if value =~ /^\d+$/ then value.to_i else value end end end end server_stats["#{server.host}:#{server.port}"] = stats end end server_stats end |
#with_server(key) ⇒ Object
606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'lib/memcache.rb', line 606 def with_server(key) retried = false begin server, cache_key = request_setup(key) yield server, cache_key rescue IndexError => e if !retried && @servers.size > 1 puts "Connection to server #{server.inspect} DIED! Retrying operation..." retried = true retry end handle_error(nil, e) end end |
#with_socket_management(server, &block) ⇒ Object
Gets or creates a socket connected to the given server, and yields it to the block. If a socket error (SocketError, SystemCallError, IOError) or protocol error (MemCacheError) is raised by the block, closes the socket, attempts to connect again, and retries the block (once). If an error is again raised, reraises it as MemCacheError. If unable to connect to the server (or if in the reconnect wait period), raises MemCacheError - note that the socket connect code marks a server dead for a timeout period, so retrying does not apply to connection attempt failures (but does still apply to unexpectedly lost connections etc.).
Wraps the whole lot in mutex synchronization if @multithread is true.
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 |
# File 'lib/memcache.rb', line 588 def with_socket_management(server, &block) @mutex.lock if @multithread retried = false begin socket = server.socket # Raise an IndexError to show this server is out of whack. # We'll catch it in higher-level code and attempt to restart the operation. raise IndexError, "No connection to server (#{server.status})" if socket.nil? block.call(socket) rescue MemCacheError, SocketError, SystemCallError, IOError => err handle_error(server, err) if retried || socket.nil? retried = true retry end ensure @mutex.unlock if @multithread end |