欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET 使用CouchBase 基础篇

程序员文章站 2023-03-26 11:15:30
这里不介绍couchbase的安装,只介绍.NET Client Librarye 使用。   获得CouchBase For Net的SDK有两种方式 通过nug...
这里不介绍couchbase的安装,只介绍.NET Client Librarye 使用。

 

获得CouchBase For Net的SDK有两种方式

通过nuget,Install-Package CouchbaseNetClient

通过官网下载https://www.couchbase.com/communities/net

 

 

开始CouchBase之旅

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

 

 

在程序中配置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="https://192.168.0.2:8091/pools"/>

      <add uri="https://192.168.0.3:8091/pools"/>

    </servers>

  </couchbase>

</configuration>

 

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

 

 

 

添加引用

using Couchbase;

 

using Couchbase.Configuration;

 

using Couchbase.Extensions;

 

using Enyim.Caching;

 

using Enyim.Caching.Configuration;

 

using Enyim.Caching.Memcached;

 

根据实际引用添加引用

 

 

 

创建实例及使用

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

 

 

 

检查和操作结果

官方的说明

 

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

}

 

 

 

获取详细操作结果

如果你需要获取运行时的详细信息,你可以使用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);

}

 

 

 

配置日志

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>

 

 

 

 

 

 

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>