.NET 使用CouchBase 基礎篇


 

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源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM