使用Mongodb 做对象缓存
mongodb高效的访问速度,用来快速存取数据再合适不过了,缓存神马的,可以用这个的
另外,有的时候,如果仅仅存储几条数据,单独去建立一张表代价太大,这个时候,不妨试试这个
先发一个mongodb数据访问帮助类
<p> public class MongdbHelper : IDisposable { public MongoServer Server { get ; private set ; } public MongoDB.Driver.MongoDatabase Database { get ; private set ; } public MongoCollection<bsondocument> 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<t> GetOnColumn<t>( string dbName, string tableName, string column, Func< object , t= "" > convert) { try { using (MongdbHelper db = new MongdbHelper(dbName, tableName)) { List<t> results = new List<t>(); var r = db.DataSet.FindAll(); r.SetFields(column); foreach ( var c in r) { results.Add(convert(c[column])); } return results; } } catch { return null ; } } public static bool IsExist( string dbName, string tableName, string column, object value) { try { using (MongdbHelper db = new MongdbHelper(dbName, tableName)) { IMongoQuery query = new QueryDocument() { { column, value.ToString() } }; var results = db.DataSet.FindOne(query); return results != null ; } } catch { return false ; } } }</t></t></ object ,></t></t></bsondocument></p> |
再来看具体的实现:
原理:将对象通过序列化操作后以二进制的方式存储到mongodb中
存实现:
/// <summary> /// 存储数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"> /// <param name="value"> public static void Set<t>( 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< string ,= "" object = "" > newDict = new Dictionary< string ,= "" object = "" >(); 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); } }</ string ></ string ></t> |
取实现:
/// <summary> /// 获取对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"> /// <returns></returns> public static T Get<t>( string key) { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IDictionary< string ,= "" object = "" > dict = new Dictionary< string ,= "" object = "" >(); 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<t>(bytes); } else { return default (T); } #endregion } catch { return default (T); } } return default (T); } }</t></ string ></ string ></t> |
另外,为了方便存储单个对象的数据,例如配置信息,增加下面两个方法:
/// <summary> /// 存储对象 /// 适用于只有单个对象或单条记录的数据,例如系统配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"> public static void Set<t>(T value) { Set( typeof (T).Name, value); } /// <summary> /// 获取对象 /// 适用于只有单个对象或单条记录的数据,例如系统配置 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Ge<t>() { return Get<t>( typeof (T).Name); }</t></t></t> |
完整代码:
public class SerializeHelper { /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serializedObject"> /// <returns></returns> public static T BinaryDeSerialize<t>( 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; } /// <summary> /// 序列化 /// </summary> /// <param name="obj"> /// <returns></returns> 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; } } /// <summary> /// 简易的mongodb数据存储服务 /// </summary> public class DataService { /// <summary> /// 数据接名 /// </summary> static string DefaultDbName = "MongodbService" ; static string DefaultTableName = "DataSet" ; /// <summary> /// 获取对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"> /// <returns></returns> public static T Get<t>( string key) { using (MongdbHelper db = new MongdbHelper(DefaultDbName, DefaultTableName)) { IDictionary< string ,= "" object = "" > dict = new Dictionary< string ,= "" object = "" >(); 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<t>(bytes); } else { return default (T); } #endregion } catch { return default (T); } } return default (T); } } /// <summary> /// 存储数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"> /// <param name="value"> public static void Set<t>( 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< string ,= "" object = "" > newDict = new Dictionary< string ,= "" object = "" >(); 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); } } /// <summary> /// 存储对象 /// 适用于只有单个对象或单条记录的数据,例如系统配置 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"> public static void Set<t>(T value) { Set( typeof (T).Name, value); } /// <summary> /// 获取对象 /// 适用于只有单个对象或单条记录的数据,例如系统配置 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T Ge<t>() { return Get<t>( typeof (T).Name); } }</t></t></t></ string ></ string ></t></t></ string ></ string ></t></t> |
使用举例:
有这个一个用户类:
/// <summary> /// 简易的用户模型 /// </summary> [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<usermodel>( this .CurrentUserName); if (currentUser == null ) { var user = IoC.Resolve<iuserrepository>().FindByAccountName(CurrentUserName); if (user != null ) { currentUser = new UserModel { UserName = CurrentUserName, Name = user.Name, UserId = user.ID }; // 保存到mongodb 长久存储 DataService.Set<usermodel>( this .CurrentUserName, currentUser); } } } } return currentUser; } }</usermodel></iuserrepository></usermodel> |
关注作者
作者: JadePeng
出处:https://www.cnblogs.com/xiaoqi/archive/2012/03/15/2398014.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际(欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接) 」知识共享许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了