代码改变世界

.NET 使用CouchBase 基础篇

2014-01-27 17:19  Eric.Hu  阅读(2564)  评论(4编辑  收藏  举报

 

2011年2月,CouchOne和memebase合并后,改名为Couchbase,官网地址(www.couchbase.com)。membase最后一个版本为1.7.2,可在Couchbase的官网下载(http://www.couchbase.com/downloads-all)。

这里不介绍couchbase的安装,只介绍.NET Client Librarye 使用。

  1. 获得CouchBase For Net的SDK有两种方式
    1. 通过nuget,Install-Package CouchbaseNetClient
    2. 通过官网下载http://www.couchbase.com/communities/net

     

  2. 开始CouchBase之旅
    1. 创建项目,这里需要提醒的是,在vs2010中我们创建类Console应用程序时项目默认使用.NET Framework Client Profile,我们需要手动切换至full .NET Framework

       

    2. 在程序中配置CouchBase,CouchBase提供编码配置和配置文件配置,当然使用app.config是最灵活的,这里是我们的首选,添加以下信息至你的配置文件,

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase"/>
      </configSections>
      <couchbase>
        <servers bucket="default" bucketPassword="">
          <add uri="http://192.168.0.2:8091/pools"/>
          <add uri="http://192.168.0.3:8091/pools"/>
        </servers>
      </couchbase>
    </configuration>

    这里使用了集群配置的url列表,当然在你本地调试只需要一个地址,默认CouchBase在安装时会创建一个没有密码的default的缓存桶(bucket),你可以自由修改这块的信息。(如果对bucket不太明白,请自行google)。

     

    1. 添加引用

using Couchbase;

using Couchbase.Configuration;

using Couchbase.Extensions;

using Enyim.Caching;

using Enyim.Caching.Configuration;

using Enyim.Caching.Memcached;

根据实际引用添加引用

 

  1. 创建实例及使用

var client = new CouchbaseClient(); // 创建实例

client.Store(StoreMode.Add, "somekey", "somevalue"); //存储数据

var someValue = client.Get("somekey") as string; //获取数据

var someValue = client.Get<string>("somekey"); //获取数据

以上是简单基本类型的使用,下面我们介绍一下复杂类型。先申明一个类

[Serializable]
public class Beer {
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Brewery { get; set; }
}

 

var key = Guid.NewGuid();
var beer =
new Beer {
    Id = key,
    Name = "Old Yankee Ale",
    Brewery = "Cottrell Brewing Company"
};
client.Store(StoreMode.Add, "beer_" + key, beer);

 

var beer = client.Get<Beer>("beer_" + key);

 

在CouchBase2.0正式版就开始支持json,这一点让人激动人心。

 

存储json数据

public static bool StoreJson<T>(this CouchbaseClient client, StoreMode storeMode, string key, T value) where T : class {
    var ms = new MemoryStream();
    var serializer = new DataContractJsonSerializer(typeof(T));
    serializer.WriteObject(ms, value);
    var json =
Encoding.Default.GetString(ms.ToArray());
    ms.Dispose();
    return client.Store(storeMode, key, json);            
}

 

获取json数据

public static T GetJson<T>(this CouchbaseClient client, string key) where T : class {    
    var json = client.Get<string>(key);    
    var ms = new
MemoryStream(
Encoding.Default.GetBytes(json));
    var serializer =
new
DataContractJsonSerializer(typeof(
T));                            
    var obj = serializer.ReadObject(ms) as T;
    ms.Dispose();
    return obj;
                       
}

 

Client使用方法

var key = Guid.NewGuid();
var beer = new Beer {
    Id = key,
    Name = "American Ale",
    Brewery = "Thomas Hooker Brewing Company",
    Type = "beer"
};
client.StoreJson<Beer>(StoreMode.Add, "beer_" + key, beer);

var beer = client.GetJson<Beer>("beer_" + key);

 

  1. 检查和操作结果

    官方的说明

    For check and set operations, the return values are wrapped in a CasResult instance.  The success of the operation is still determined by a Boolean and detailed failures still require logging. 

var result = client.GetWithCas("foo");
var bar = "bar";
var result = client.Cas(StoreMode.Set, "foo", bar, result.Cas);
if (result.Result) {
   Console.WriteLine("CAS operation was successful");
}

 

  1. 获取详细操作结果

    如果你需要获取运行时的详细信息,你可以使用IoperationResult API方法,下面是官方给的API属性的说明。

    Each of these methods shares its name with a method from the single-value return API, but prefixed with "Execute." For example, Get() becomes ExecuteGet() and Store() becomes ExecuteStore().

 

Property

Interface

Description

Success

IOperationResult

Whether the operation succeeded

Message

IOperationResult

Error, warning or informational message

StatusCode

IOperationResult

Nullable status code from server

InnerResult

IOperationResult

Nested result.  Populated by low-level I/O failures.

Value

INullableOperationResult

Extended by IGetOperationResult, where Value is item for given key. 

HasValue

INullableOperationResult

Shortcut for null Value check. 

Cas

ICasOperationResult

Extended by IGetOperationResult, IMutateOperationResult, IConcatOperationResult and IStoreOperationResult.  Contains possible CAS value for operations.

var getResult = client.ExecuteGet<Beer>("beer_heady_topper");
if (getResult.Success && getResult.HasValue) {  
   

   var beer = getResult.Value;
   beer.Brewery =
"The Alchemist";
   var casResult = client.ExecuteCas(StoreMode.Set, "beer_heady_topper", beer, getResult.Cas);

   if (casResult.Success) {
       Console.WriteLine("CAS operation was successful");
   }

} else {
   Console.WriteLine("Get operation failed with message {0} and exception {1} ",
                          getResult.Message, getResult.Exception);
}

 

  1. 配置日志

    CouchBase支持Log4Net和Nlog,你可以自己现在或者从CouchBase提供的SDK获取。

     

    Log4Net 配置参考。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="enyim.com">
      <section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />
    </sectionGroup>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <enyim.com>
    <log factory="Enyim.Caching.Log4NetFactory, Enyim.Caching.Log4NetAdapter" />
  </enyim.com>
  <log4net debug="false">
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net">
      <param name="File" value="c:\\temp\\error-log.txt" />
      <param name="AppendToFile" value="true" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
      </layout>
    </appender>
    <root>
      <priority value="ALL" />
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>  
</configuration>

更多Log4Net配置可参考:http://logging.apache.org/log4net/release/manual/configuration.html.

 

 

Nlog配置参考

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="enyim.com">
      <section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />
    </sectionGroup>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <enyim.com>
    <log factory="Enyim.Caching.NLogFactory, Enyim.Caching.NLogAdapter" />
  </enyim.com>
  <nlog>
    <targets>
      <target name="logfile" type="File" fileName="c:\temp\error-log.txt" />
    </targets>
    <rules>
      <logger name="*" minlevel="Info" writeTo="logfile" />
    </rules>
  </nlog>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
</configuration>

更多Nlog配置可参考:http://nlog-project.org/wiki/Configuration_file

 

 

总结 :以上信息来源官方的Getting Started,另附一份自己整理的Demo。(通过office word 发布的文档格式有些变形)

Demo源码