1

我正在编写一个包装器 api 来提供一个 Set 方法,类似于:

Set(string bucket, string key, object value)

我需要的是,如果提供的存储桶不可用——我需要使用默认存储桶,否则将其存储到特定存储桶。

我能想到的一种方法是在 try...catch 块中使用提供的存储桶实例化 CouchbaseClient,如果失败将其存储在默认存储桶中。有没有更好的办法?

4

1 回答 1

1

一般来说,您不想实例化每个请求的客户端。第一次连接到集群的开销并不小。因此,建议您为每个存储桶、每个应用程序域创建一个静态实例。客户端也具有存储桶亲和性,因此您无法在不重新实例化客户端的情况下切换存储桶。

有关配置多个存储桶的信息,请参阅http://www.couchbase.com/wiki/display/couchbase/Couchbase+.NET+Client+Library

如果您按照上述方式创建多个存储桶配置部分,您的方法可能类似于:

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);
}

我实际上并没有运行这段代码,但是这样的东西应该可以工作。请记住,您必须有一个匹配的配置部分。因此,使用 wiki 示例,您的字典中有两个键 - “bucket-a”和“bucket-b”。

客户端的下一个版本将支持通过 REST API 查询存储桶,但这会稍微影响性能。这些位应该很快就会作为 Developer Preview 4 删除。在这种情况下,您将能够添加对新 CouchbaseCluster 对象的 ListBuckets 方法的调用并检查返回列表中的存储桶。如果该存储桶存在,您可以缓存其关联的 CouchbaseClient。

于 2012-09-06T21:42:18.213 回答