1、下载驱动:
如下图:选择c#解决方案,右键,点击 “管理NuGet程序包(N)...”
在弹出的对话框中,输入MongoDB.Driver,进行搜索,然后选择安装。
2、引用命名空间:
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;
3、程序代码
配置文件:
public class iCTRMongodbCache : CacheBase
{
IMongoCollection<BsonDocument> _collect;
IMongoDatabase _db;
string _collectionName = "";
/// <summary>
/// 默认搜索列字段名称
/// </summary>
string defaultColumn = ConfigurationManager.AppSettings["DefaultColumn"].ToString();
/// <summary>
/// 构造函数
/// </summary>
/// <param name="collectionName">集合名称,类似关系型数据库中的表名</param>
public iCTRMongodbCache(string collectionName)
: base(collectionName)
{
_collectionName = collectionName;
string mongoDB_Host = ConfigurationManager.AppSettings["MongoDB_Host"].ToString();
string mongoDB_DbName = ConfigurationManager.AppSettings["MongoDB_DbName"].ToString();
string mongoDB_UserName = ConfigurationManager.AppSettings["MongoDB_UserName"].ToString();
string mongoDB_Password = ConfigurationManager.AppSettings["MongoDB_Password"].ToString();
MongoDB.Driver.MongoClient mc = new MongoClient(mongoDB_Host);
_db = mc.GetDatabase(mongoDB_DbName);
_collect = _db.GetCollection<BsonDocument>(collectionName);
}
public override bool Append(string keyValue, string value)
{
if (string.IsNullOrEmpty(value) || value.IndexOf(":") < 0)
{
return false;
}
Dictionary<string, string> dictR = new Dictionary<string, string>();
dictR.Add(defaultColumn, keyValue);
try
{
string[] values = value.Split(‘,‘);
foreach (string keyv in values)
{
dictR.Add(keyv.Split(‘:‘)[0], keyv.Split(‘:‘)[1]);
}
BsonDocument bd = new BsonDocument();
bd.AddRange(dictR);
_collect.InsertOne(bd);
}
catch (System.InvalidOperationException ex)
{
throw ex;
}
return true;
}
public override object Get(string keyValue)
{
Dictionary<string,object> dict =new Dictionary<string,object>();
dict.Add(defaultColumn, keyValue);
var query = new BsonDocument(dict);
IAsyncCursor<BsonDocument> result = _collect.FindSync(query);
List<BsonDocument> list = null;
if (result.MoveNext())
{
list = result.Current as List<BsonDocument>;
}
return list;
}
public override T Get<T>(string keyValue)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add(defaultColumn, keyValue);
var query = new BsonDocument(dict);
IAsyncCursor<BsonDocument> result = _collect.FindSync(query);
if (result.MoveNext())
{
List<BsonDocument> list = result.Current as List<BsonDocument>;
if (list != null)
{
BsonDocument bd = list[0];
bd.Remove("_id");
bd.Remove(defaultColumn);
JavaScriptSerializer Serializer = new JavaScriptSerializer();
Serializer.MaxJsonLength = int.MaxValue;
return Serializer.Deserialize<T>(bd.ToString());
}
else
{
return default(T);
}
}
else
{
return default(T);
}
}
public override void Set(string keyValue, object value, DateTime expiration)
{
Dictionary<string, object> dictR = new Dictionary<string, object>();
dictR.Add(defaultColumn, keyValue);
try
{
BsonDocument bd = value.ToBsonDocument();
bd.AddRange(dictR);
_collect.InsertOne(bd);
}
catch (System.InvalidOperationException ex)
{
throw ex;
}
}
public override void Set<T>(string keyValue, T value)
{
Dictionary<string, object> dictR = new Dictionary<string, object>();
dictR.Add(defaultColumn, keyValue);
try
{
BsonDocument bd = value.ToBsonDocument<T>();
bd.AddRange(dictR);
_collect.InsertOne(bd);
}
catch (System.InvalidOperationException ex)
{
throw ex;
}
}
public override void Remove(string key)
{
Dictionary<string, object> dictR = new Dictionary<string, object>();
dictR.Add(defaultColumn, key);
_collect.DeleteOne(new BsonDocument(dictR));
}
public override void Clear()
{
_db.DropCollection(_collectionName);
}
public override void Dispose()
{
_db.DropCollection(_collectionName);
_collect = null;
}
}
4、测试代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongodbCache.Caching;
namespace UnitTest
{
[TestClass]
public class iCTRMongodbCacheTest
{
private iCTRMongodbCache _cache;
public iCTRMongodbCacheTest()
{
_cache = new iCTRMongodbCache("test1");
}
[TestMethod]
public void TestAppend()
{
//ID454为主键字段对应的数据,"age:43,name:Marry为要插入的数据,
//调用缓存的Append方法,第二个参数必须为类似"column1 : column1Value,column2 : column2Value "的数据
_cache.Append("ID1", "age:43,name:Marry");
}
[TestMethod]
public void TestSet1()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("age", "12");
dict.Add("Name", "Marry");
_cache.Set("ID2", dict);
}
[TestMethod]
public void TestSet2()
{
student s = new student();
s.age = 234;
s.name = "lengli";
_cache.Set<student>("ID3", s);
}
[TestMethod]
public void TestRemove()
{
string ID = "ID1";
_cache.Remove(ID);
}
[TestMethod]
public void TestGet1()
{
object obj = _cache.Get("ID2");
}
[TestMethod]
public void TestGet2()
{
student dd = _cache.Get<student>("ID3");
}
[TestMethod]
public void TestClear()
{
_cache.Clear();
}
[TestClass]
class student
{
public string name
{
get;
set;
}
public int age
{
get;
set;
}
}
}
}