Included Modules

EventMachine::Protocols::Memcache

Implements the Memcache protocol (code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt). Requires memcached >= 1.2.4 w/ noreply support

Usage example

EM.run{
  cache = EM::P::Memcache.connect 'localhost', 11211

  cache.set :a, 'hello'
  cache.set :b, 'hi'
  cache.set :c, 'how are you?'
  cache.set :d, ''

  cache.get(:a){ |v| p v }
  cache.get_hash(:a, :b, :c, :d){ |v| p v }
  cache.get(:a,:b,:c,:d){ |a,b,c,d| p [a,b,c,d] }

  cache.get(:a,:z,:b,:y,:d){ |a,z,b,y,d| p [a,z,b,y,d] }

  cache.get(:missing){ |m| p [:missing=, m] }
  cache.set(:missing, 'abc'){ p :stored }
  cache.get(:missing){ |m| p [:missing=, m] }
  cache.del(:missing){ p :deleted }
  cache.get(:missing){ |m| p [:missing=, m] }
}

Public Class Methods

connect(host = 'localhost', port = 11211) click to toggle source

Connect to a memcached server (must support NOREPLY, memcached >= 1.2.4)

# File lib/em/protocols/memcache.rb, line 109
def self.connect host = 'localhost', port = 11211
  EM.connect host, port, self, host, port
end

Public Instance Methods

del(key, expires = 0, &cb) click to toggle source
Alias for: delete
delete(key, expires = 0, &cb) click to toggle source

Delete the value associated with a key

cache.del :a
cache.del(:b){ puts "deleted the value!" }
# File lib/em/protocols/memcache.rb, line 100
def delete key, expires = 0, &cb
  callback{
    send_data "delete #{key} #{expires}#{cb ? '' : ' noreply'}\r\n"
    @del_cbs << cb if cb
  }
end
Also aliased as: del
get(*keys) click to toggle source

Get the value associated with one or multiple keys

cache.get(:a){ |v| p v }
cache.get(:a,:b,:c,:d){ |a,b,c,d| p [a,b,c,d] }
# File lib/em/protocols/memcache.rb, line 56
def get *keys
  raise ArgumentError unless block_given?

  callback{
    keys = keys.map{|k| k.to_s.gsub(/\s/,'_') }
    send_data "get #{keys.join(' ')}\r\n"
    @get_cbs << [keys, proc{ |values|
      yield *keys.map{ |k| values[k] }
    }]
  }
end
get_hash(*keys) click to toggle source

Gets multiple values as a hash

cache.get_hash(:a, :b, :c, :d){ |h| puts h[:a] }
# File lib/em/protocols/memcache.rb, line 87
def get_hash *keys
  raise ArgumentError unless block_given?

  get *keys do |*values|
    yield keys.inject({}){ |hash, k| hash.update k => values[keys.index(k)] }
  end
end
set(key, val, exptime = 0, &cb) click to toggle source

Set the value for a given key

cache.set :a, 'hello'
cache.set(:missing, 'abc'){ puts "stored the value!" }
# File lib/em/protocols/memcache.rb, line 73
def set key, val, exptime = 0, &cb
  callback{
    val = val.to_s
    send_cmd :set, key, 0, exptime, val.respond_to?(:bytesize) ? val.bytesize : val.size, !block_given?
    send_data val
    send_data Cdelimiter
    @set_cbs << cb if cb
  }
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.