Skip to content

Instantly share code, notes, and snippets.

@mje113
Created October 4, 2013 09:33
Show Gist options
  • Save mje113/6823395 to your computer and use it in GitHub Desktop.
Save mje113/6823395 to your computer and use it in GitHub Desktop.
Example usage of Couchbase Java SDK 1.2.0 callbacks on an async set (in JRuby).
module Couchbase
class AsyncCallback
include Java::NetSpyMemcachedInternal::OperationCompletionListener
def initialize(callback)
@callback = callback
end
def onComplete(future)
@callback.call(future)
end
end
class Bucket
attr_reader :client
def initialize(options = {})
@connection_factory = CouchbaseConnectionFactory.new(uris, bucket.to_java_string, password.to_java_string)
@client = CouchbaseClient.new(@connection_factory)
end
def set(key, value, options = {}, &block)
ttl = options[:ttl] || default_ttl
if async?
async_set(key, value, ttl, &block)
else
future = client.set(key, ttl, value)
if future.get
future.getCas
else
raise Error::KeyExists.new
end
end
end
def async_set(key, value, ttl, &block)
future = client.set(key, ttl, value)
if block_given?
callback = Couchbase::AsyncCallback.new(block)
future.addListener(callback)
end
end
def run
# details removed for brevity
@async = true
if block_given?
yield(self)
end
ensure
@async = false
end
def async?
!!@async
end
end
end
bucket = Couchbase::Bucket.new
bucket.run do
bucket.set('foo', 'bar') { |future| puts future.isSuccess }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment