博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Mongodb 做对象缓存
阅读量:5312 次
发布时间:2019-06-14

本文共 10664 字,大约阅读时间需要 35 分钟。

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 convert) { try { using (MongdbHelper db = new MongdbHelper(dbName, tableName)) { List results = new List(); 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; } } }

 

再来看具体的实现:

原理:将对象通过序列化操作后以二进制的方式存储到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;            }        }

转载于:https://www.cnblogs.com/xiaoqi/archive/2012/03/15/2398014.html

你可能感兴趣的文章
狗熊掰棒子之重拾棒子之JavaScript篇
查看>>
flavor用法
查看>>
upbeat用法
查看>>
IE浏览器样式表限制
查看>>
linux sar命令详解
查看>>
bzoj1055[HAOI2008]玩具取名 区间dp
查看>>
bzoj4152[AMPPZ2014]The Captain 最短路
查看>>
Java Memory Model
查看>>
java 抓取百度根据关键词搜索域名
查看>>
(转载)zeromq使用注意点滴
查看>>
【转】人类的心理行为模式----《影响力》笔记
查看>>
hdu 4176
查看>>
poj 1426 Find The Multiple (BFS)
查看>>
Ref和Out参数的区别(转帖)
查看>>
性能学习之--loaderunner压测
查看>>
C#的闭包
查看>>
Android实现微信自己主动抢红包的程序
查看>>
从计算的本质到编程语言
查看>>
《罗辑思维》的逻辑缺陷
查看>>
IAR编译duplicate definitions for IAR报错解决办法补充版
查看>>