Reputation: 79
I am writing a wrapper api to provide a Set method, something similar to:
Set(string bucket, string key, object value)
What I need is, if a supplied bucket is not available -- I need to use default bucket, otherwise Store it to specific bucket.
One way I can think of is to instantiate the CouchbaseClient with supplied bucket inside a try...catch block and if that fails Store it in default bucket. Is there a better way?
Upvotes: 1
Views: 729
Reputation: 1592
Generally speaking, you don't want to instantiate a client-per-request. The overhead of connecting to the cluster the first time is not trivial. It's therefore recommended that you create a static instance per bucket, per app domain. A client has bucket affinity as well, so you can't switch buckets without reinstantiating the client.
For information on configuring multiple buckets, see http://www.couchbase.com/wiki/display/couchbase/Couchbase+.NET+Client+Library.
If you create multiple bucket config sections as per above, you could have your method be something like:
private static Dictionary<string, CouchbaseClient> _clientDict = new Dictionary<string, CouchbaseClient>();
public IStoreResult Set(string key, object value, string bucketName, string bucketPassword = "")
{
if (! _clientDict.ContainsKey(bucketName))
{
_clientDict[bucketName] = new CouchbaseClient(bucketName); //assume this matches the config section name
}
return _clientDict[bucketName].ExecuteStore(StoreMode.Set, key, value);
}
I haven't actually run this code, but something like this should work. Just remember you'd have to have a matching config section. So using the wiki example, you'd have two keys in your dictionary - "bucket-a" and "bucket-b."
The next release of the client will support querying for buckets over the REST API, but that would impact performance a touch. Those bits should drop as Developer Preview 4 shortly. In that case, you will be able to add a call to the new CouchbaseCluster object's ListBuckets method and check for a bucket in the return list. If that bucket exists, you could cache its associated CouchbaseClient.
Upvotes: 1