使用Mongodb 做對象緩衝

來源:互聯網
上載者:User

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;            }        }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.