Starting from scratch, build a blog system Mvc5+ef6 frame (3), add Nlog log, caching mechanism (memorycache, Rediscache), create Controller parent class Basecontroller

Source: Internet
Author: User
Tags redis serialization

I. Review of system progress and summary of this chapter

The current blog system has been database creation, and dependency injection AUTOFAC integration, the next is the log and cache integration, where the log is nlog, in fact there are other log frames such as LOG4, these blog park has a lot of introductions, here will not say, Caching mechanism with the Microsoft MemoryCache and the more popular Redis, here I also just understand the use, did not do a more research, after a good study of Redis, Then there is the implementation of a Basecontroller parent class used to override the Jsonresult method in order to return the time format problem, and the default JSON returns the time format that date (84923838332223) is converted to a common YYYY-MM-DD hh:mm: SS-format.

II. Implementation of caching mechanism

1. Create a file in the public assembly plus a cache to store the cached class, and one log is used to create the Nlog class, which is implemented using an interface so that you can achieve multiple implementations later.

2, first create a Icachemanager interface class.

  1 namespace Wchl.WMBlog.Common.Cache
  2 {
  3 public     interface Icachemanager
  4     {
  5        ///< Summary>
  6        ///get
  7        ///</summary>
  8        ///<typeparam name= "Tentity" >< /typeparam>
  9        ///<param name= "key" ></param>        ///<returns></ returns>         tentity get<tentity> (string key);         set         void Set (String key, Object value, TimeSpan cacheTime);
 I         //judge if there is a         bool Contains (string key);
 /         /removal of         void Remove (string key);
 /         /clear the         void Clear ();
 22}
View Code

3, in the implementation of Microsoft caching mechanism need to refer to System.Runtime.Caching.dll, create a Memorycachemanager class

  1 namespace Wchl.WMBlog.Common.Cache
  2 {
  3      public  class Memorycachemanager:icachemanager
  4     {
  5 public         void Clear ()
  6         {
  7 
  8             foreach (var item in Memorycache.default)
  9             {
 this                 . Remove (item. Key);
 All             public         bool Contains (string key)         {             MemoryCache.Default.Contains (key);
 The         public         tentity get<tentity> (string key)         {             tentity) MemoryCache.Default.Get (key);
 A         public         void Remove (string key)             MemoryCache.Default.Remove (key);
 The         public         void Set (String key, Object value, TimeSpan cacheTime)         {
 31             MemoryCache.Default.Add (key, value, new CacheItemPolicy {slidingexpiration = cacheTime});         34}
 
View Code

4, the Realization Rediscachemanager class, here we use the Free Redis customer service end is Stackexchange.redis. can be downloaded to in NuGet.

Rediscachemanager class

  1 namespace Wchl.WMBlog.Common.Cache 2 {3 public class Rediscachemanager:icachemanager 4 {5
  Private readonly string redisconnenctionstring;
  6 7 public volatile connectionmultiplexer redisconnection;
 8 9 Private ReadOnly Object redisconnectionlock = new Object (); All public Rediscachemanager () 12 {13//LINK Redis Service statement-string Redisconfigu ration = configurationmanager.connectionstrings["Rediscache"].
 ToString (); if (string.  Isnullorwhitespace (redisconfiguration)) {throw new ArgumentException ("Redis config is
 Empty ", nameof (redisconfiguration));
 this.redisconnenctionstring = redisconfiguration;
 This.redisconnection = Getredisconnection (); Private Connectionmultiplexer Getredisconnection () () (This.re Disconnection!= null &Amp;& this.redisConnection.IsConnected) {return this.redisconnection;  Lock (Redisconnectionlock) to {if (this.redisconnection != null) 33 {34//Free Redis connection This.redisConnection.Dispose ()
 ;
 Panax Notoginseng this.redisconnection = Connectionmultiplexer.connect (redisconnenctionstring);
 This.redisconnection return; EndPoint is public void clear (), and the Var is in this. Getredisconnection (). Getendpoints ()) {MB var server = this. Getredisconnection ().
 Getserver (EndPoint); The $ foreach (var key in server). Keys ()) Redisconnection.getdatabase ().
 Keydelete (key);     50} 51} 52} 53 54    public bool Contains (string key)-Redisconnection.getdatabase return ().
 Keyexists (key); Tentity public get<tentity> (string key) {$ var value = Redi Sconnection.getdatabase ().
 Stringget (key); An if (value.
 HasValue) serializehelper.deserialize<tentity> (value);
 (tentity) Else () Redisconnecti public void Remove (string key). On. Getdatabase ().
 Keydelete (key);             TimeSpan public void Set (string key, Object value, CacheTime) 77 {78 if (value!= null) is {redisconnection.getdatabase ().
 Stringset (Key, Serializehelper.serialize (value), cacheTime); 81} 82} 83} 84}
View Code

This is used to serialize and deserialize when storing data, and the serialization tool used is Newtonsoft.json and can also be found in NuGet.

Serializehelper serialization Help Class

  1 namespace Wchl.WMBlog.Common 2 {3 public class Serializehelper 4 {5///<summary> 6 Serialization 7///</summary> 8///<param name= "Item" ></param> 9///& lt;returns></returns> public static byte[] Serialize (object) one {var j
 sonstring = Jsonconvert.serializeobject (item);
 Return Encoding.UTF8.GetBytes (jsonstring); ///<summary> 17///deserialized///</summary>///<typ Eparam name= "tentity" ></typeparam>///<param name= "value" ></param>///<r             eturns></returns> public static tentity deserialize<tentity> (byte[] value) 23 {24
 if (value = = null) {return default (tentity); var jsonstring = Encoding.UTF8.
 GetString (value);
 Return jsonconvert.deserializeobject<tentity> (jsonstring); 30} 31} 32}
View Code

third, log processing: Nlog log frame

1, first realize a day interface ILogger

  1 namespace Wchl.WMBlog.Common.Log
  2 {
  3 public     interface ILogger
  4     {
  5         void Debug ( String message);
  6         void Debug (String message, Exception Exception);
  7         void Error (String message);
  8         void Error (String message, Exception Exception);
  9         void Fatal (String message);         a void Fatal (String message, Exception Exception);
 One         void Info (String message);         void Info (String message, Exception Exception);         void Warn (String message);         Warn (String message, Exception Exception);     }
 16}
View Code

2. Add the Nlog frame to the NuGet

Nlog.config is the configuration file for the log frame.

Nloglogger class

  1 namespace Wchl.WMBlog.Common.Log 2 {3 public class Nloglogger:ilogger 4 {5 Private readonl
  Y Logger Logger = Logmanager.getcurrentclasslogger (); 6 public void Debug (String message) 7 {8 logger.
  Debug (message); 9} public void Debug (String message, Exception Exception) LOGGER.D
 Ebug (exception, message); {Logger is the public void Error (String message).
 Error (message); The public void Error (string, Exception Exception) is logger.
 Error (exception, message); The public void Fatal (String message) is logger.
 Fatal (message); The public void Fatal (String message, Exception Exception) is logger.
 Fatal (exception, message); The public VOID Info (String message) (logger).
 Info (message); The public void Info (String message, Exception Exception) is {logger.i
 NFO (exception, message);
 Warn public void (String message)

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.