1 public static class CouchBaseHelper
2 {
3 static CouchBaseHelper()
4 {
5 ClusterHelper.Initialize("couchbaseClients/couchbase");
6 }
7
8 /// <summary>
9 /// Documents the exist.
10 /// </summary>
11 /// <param name="key">The key.</param>
12 /// <param name="bucketName">Name of the bucket.</param>
13 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
14 public static bool DocumentExist(string key, string bucketName = "xftbmb")
15 {
16 var bucket = ClusterHelper.GetBucket(bucketName);
17
18 return bucket.Exists(key);
19
20
21 }
22
23
24 /// <summary>
25 /// 在Bucket中获取一个文档
26 /// </summary>
27 /// <typeparam name="T">动态数据类型</typeparam>
28 /// <param name="key">文档唯一标识</param>
29 /// <param name="bucketName">指定Bucket名称</param>
30 /// <returns></returns>
31 public static T DocumentGet<T>(string key, string bucketName = "xftbmb")
32 {
33 try
34 {
35 var bucket = ClusterHelper.GetBucket(bucketName);
36
37 var result = bucket.GetDocument<T>(key);
38 if (result.Success)
39 {
40 return result.Content;
41 }
42 return default(T);
43
44 }
45 catch (Exception)
46 {
47
48 return default(T);
49 }
50
51 }
52
53
54 /// <summary>
55 /// 在Bucket中添加/更新一个文档
56 /// </summary>
57 /// <typeparam name="T">动态数据类型, The actual document value to store. This can be a scalar value, an object, or a dynamic type.</typeparam>
58 /// <param name="key">文档唯一标识</param>
59 /// <param name="content">动态数据</param>
60 /// <param name="expiry">过期时间(秒),如果小于或等于0表示持久存在</param>
61 /// <param name="bucketName">指定Bucket名称</param>
62 /// <returns></returns>
63 public static bool DocumentUpsert<T>(string key, T content, int expiry = 0, string bucketName = "xftbmb")
64 {
65 try
66 {
67 if (expiry < 0)
68 expiry = 0;
69 var bucket = ClusterHelper.GetBucket(bucketName);
70
71 var result = bucket.Upsert(
72 new Document<T>
73 {
74 Id = key,
75 Content = content,
76 Expiry = (uint)(expiry * 1000) //将秒转换为毫秒
77 });
78 if (result.Success)
79 return true;
80 return false;
81 }
82 catch (Exception)
83 {
84
85 return false;
86 }
87
88 }
89
90
91 /// <summary>
92 /// 在Bucket中删除一个文档
93 /// </summary>
94 /// <param name="key">文档唯一标识</param>
95 /// <param name="bucketName">指定Bucket名称</param>
96 /// <returns></returns>
97 public static bool DocumentRemove(string key, string bucketName = "xftbmb")
98 {
99 var bucket = ClusterHelper.GetBucket(bucketName);
100 {
101 var result = bucket.Remove(key);
102 if (result.Success)
103 return true;
104 return false;
105 }
106 }
107 }