mongodb高效的訪問速度,用來快速存取數據再合適不過了,緩存神馬的,可以用這個的
另外,有的時候,如果僅僅存儲幾條數據,單獨去建立一張表代價太大,這個時候,不妨試試這個
先發一個mongodb數據訪問幫助類
public class MongdbHelper : IDisposable { public MongoServer Server { get; private set; } public MongoDB.Driver.MongoDatabase Database { get; private set; } public MongoCollection
DataSet { get; set; } public MongdbHelper( string dbName, string tableName) { Server = MongoServer.Create("mongodb://localhost/?socketTimeoutMS=2400000"); Database = Server.GetDatabase(dbName); DataSet = Database.GetCollection(tableName); } public MongdbHelper(string connectionString, string dbName, string tableName) { Server = MongoServer.Create(connectionString); Database = Server.GetDatabase(dbName); DataSet = Database.GetCollection(tableName); } public void Dispose() { Server.Disconnect(); } public static List GetOnColumn (string dbName, string tableName, string column, Func
再來看具體的實現:
原理:將對象通過序列化操作后以二進制的方式存儲到mongodb中
存實現:
////// 存儲數據 /// ////// /// public static void Set (string key, T value) { try { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IMongoQuery query = new QueryDocument() { {"Key",key} }; var document = db.DataSet.FindOne(query); if (document != null) { document["Value"] = SerializeHelper.BinarySerialize(value); document["Type"] = value.GetType().Name; document["Date"] = DateTime.Now.ToString(); } else { IDictionary newDict = new Dictionary (); newDict.Add("Value", SerializeHelper.BinarySerialize(value)); newDict.Add("Key", key); newDict.Add("Type", value.GetType().Name); newDict.Add("Date", DateTime.Now.ToString()); document = new BsonDocument(newDict); } db.DataSet.Save(document); } } catch (Exception ex) { throw new Exception("保存數據出錯", ex); } }
取實現:
////// 獲取對象 /// ////// /// public static T Get (string key) { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IDictionary dict = new Dictionary (); dict.Add("Key", key); IMongoQuery query = new QueryDocument() { {"Key",key} }; // 查詢 var document = db.DataSet.FindOne(query); if (document != null) { try { byte[] bytes = ((MongoDB.Bson.BsonBinaryData)document["Value"]).Bytes; #region 反序列化字節數組 if (string.Equals(document["Type"].ToString(), typeof(T).Name, StringComparison.InvariantCultureIgnoreCase)) { return SerializeHelper.BinaryDeSerialize (bytes); } else { return default(T); } #endregion } catch { return default(T); } } return default(T); } }
另外,為了方便存儲單個對象的數據,例如配置信息,增加下面兩個方法:
////// 存儲對象 /// 適用於只有單個對象或單條記錄的數據,例如系統配置 /// ////// public static void Set (T value) { Set(typeof(T).Name, value); } /// /// 獲取對象 /// 適用於只有單個對象或單條記錄的數據,例如系統配置 /// ////// public static T Ge () { return Get (typeof(T).Name); }
完整代碼:
public class SerializeHelper
{
///
/// 反序列化
///
///
///
///
public static T BinaryDeSerialize
(byte[] serializedObject)
{
MemoryStream serializationStream = new MemoryStream();
serializationStream.Write(serializedObject, 0, serializedObject.Length);
serializationStream.Seek(0L, SeekOrigin.Begin);
object obj2 = new BinaryFormatter().Deserialize(serializationStream);
serializationStream.Close();
serializationStream.Dispose();
return (T)obj2;
}
///
/// 序列化 ///
///
///
public static byte[] BinarySerialize(object obj)
{
MemoryStream serializationStream = new MemoryStream();
new BinaryFormatter().Serialize(serializationStream, obj);
serializationStream.Seek(0L, SeekOrigin.Begin);
byte[] buffer = serializationStream.ToArray();
serializationStream.Close();
serializationStream.Dispose();
return buffer;
}
}
///
/// 簡易的mongodb數據存儲服務 ///
public class DataService
{
///
/// 數據接名 ///
static string DefaultDbName = "MongodbService";
static string DefaultTableName = "DataSet";
///
/// 獲取對象 ///
///
///
///
public static T Get
(string key) { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IDictionary
dict = new Dictionary
(); dict.Add("Key", key); IMongoQuery query = new QueryDocument() { {"Key",key} }; // 查詢 var document = db.DataSet.FindOne(query); if (document != null) { try { byte[] bytes = ((MongoDB.Bson.BsonBinaryData)document["Value"]).Bytes; #region 反序列化字節數組 if (string.Equals(document["Type"].ToString(), typeof(T).Name, StringComparison.InvariantCultureIgnoreCase)) { return SerializeHelper.BinaryDeSerialize
(bytes); } else { return default(T); } #endregion } catch { return default(T); } } return default(T); } } ///
/// 存儲數據 /// ///
///
///
public static void Set
(string key, T value) { try { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IMongoQuery query = new QueryDocument() { {"Key",key} }; var document = db.DataSet.FindOne(query); if (document != null) { document["Value"] = SerializeHelper.BinarySerialize(value); document["Type"] = value.GetType().Name; document["Date"] = DateTime.Now.ToString(); } else { IDictionary
newDict = new Dictionary
(); newDict.Add("Value", SerializeHelper.BinarySerialize(value)); newDict.Add("Key", key); newDict.Add("Type", value.GetType().Name); newDict.Add("Date", DateTime.Now.ToString()); document = new BsonDocument(newDict); } db.DataSet.Save(document); } } catch (Exception ex) { throw new Exception("保存數據出錯", ex); } } ///
/// 存儲對象 /// 適用於只有單個對象或單條記錄的數據,例如系統配置 /// ///
///
public static void Set
(T value) { Set(typeof(T).Name, value); } ///
/// 獲取對象 /// 適用於只有單個對象或單條記錄的數據,例如系統配置 /// ///
///
public static T Ge
() { return Get
(typeof(T).Name); } }
使用舉例:
有這個一個用戶類:
////// 簡易的用戶模型 /// [Serializable] public class UserModel { public int UserId { get; set; } public string UserName { get; set; } public string Name { get; set; } }
可以用這樣的方式來進行存取:
public UserModel CurrentUser
{
get
{
if (currentUser == null)
{
if (!string.IsNullOrEmpty(CurrentUserName))
{
currentUser = DataService.Get
(this.CurrentUserName);
if (currentUser == null)
{
var user = IoC.Resolve
().FindByAccountName(CurrentUserName); if (user != null) { currentUser = new UserModel { UserName = CurrentUserName, Name = user.Name, UserId = user.ID }; // 保存到mongodb 長久存儲 DataService.Set
(this.CurrentUserName, currentUser); } } } } return currentUser; } }
