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