Using Mongodb for Object Caching

Source: Internet
Author: User
Tags findone

Mongodb's efficient access speed can be used to quickly access data.

In addition, it may be too costly to create a table separately if only a few pieces of data are stored.

 

Start with a mongodb data access help class

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

 

Let's take a look at the specific implementation:

Principle: objects are stored in mongodb in binary format after being serialized.

Storage implementation:

////// Store data //////
 //////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 ("failed to Save data", ex );}}
   
  
 

Implementation:

////// Get the object //////
 //////
 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 }}; // query var document = db. dataSet. findOne (query); if (document! = Null) {try {byte [] bytes = (MongoDB. bson. bsonBinaryData) document ["Value"]). bytes; # region deserialization byte array if (string. equals (document ["Type"]. toString (), typeof (T ). name, StringComparison. invariantCultureIgnoreCase) {return SerializeHelper. binaryDeSerialize
    
     
(Bytes) ;}else {return default (T) ;}# endregion} catch {return default (T );}}
    
   
  
 

In addition, to facilitate the storage of data of a single object, such as configuration information, add the following two methods:

////// Storage object // applicable to data with only one object or one record, such as system configuration //////
 ///Public static void Set
 
  
(T value) {Set (typeof (T). Name, value );}///
  /// Get object /// applicable to data with only one object or one record, for example, system configuration //////
  ///
  Public static T Ge
  
   
() {Return Get
   
    
(Typeof (T). Name );}
   
  
 

 

Complete code:

Public class SerializeHelper {////// Deserialization //////
 //////
 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 ;}///
  /// Serialization //////
  ///
  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 ;}}///
  /// Simple mongodb Data Storage Service ///Public class DataService {///
  /// Data connection name ///Static string DefaultDbName = "MongodbService"; static string DefaultTableName = "DataSet ";///
  /// Get the object //////
  ///
  ///
  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 }}; // query var document = db. dataSet. findOne (query); if (document! = Null) {try {byte [] bytes = (MongoDB. bson. bsonBinaryData) document ["Value"]). bytes; # region deserialization byte array 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 );}}///
      /// Store data //////
      ///
      ///
      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 ("failed to Save data", ex );}}///
         /// Storage object // applicable to data with only one object or one record, such as system configuration //////
         ///
         Public static void Set
         
           (T value) {Set (typeof (T). Name, value );}///
          /// Get object /// applicable to data with only one object or one record, for example, system configuration //////
          ///
          Public static T Ge
          
            () {Return Get
           
             (Typeof (T). Name );}}
           
          
         
        
       
      
     
    
   
  
 

 

Example:

There is a user class:

////// Simple user model ///[Serializable] public class UserModel {public int UserId {get; set;} public string UserName {get; set;} public string Name {get; set ;}}

You can use this method for access:

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}; // save it to the mongodb long-term storage DataService. Set
   
    
(This. CurrentUserName, currentUser) ;}}} return currentUser ;}}
   
  
 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.