C # infinitus Classification Tree-create-sort-read using Asp. Net Core + EF Method 2: Add cache mechanism,

Source: Internet
Author: User

C # infinitus Classification Tree-create-sort-read using Asp. Net Core + EF Method 2: Add cache mechanism,

In the previous article, I used recursive methods to implement the management menu. In the previous section, I also mentioned that cache should be considered. Net Core caching mechanism.

There are three official implementations of. Net Core Caching:

1. In Memory Caching I understand it is implemented In the content. This method is applicable to the production environment of a single server.

2. a Distributed Cache implementation in a segmented Cache.

3. Response Cache I understand this method as client Cache.

Today, I only used the first implementation method: cache in the memory. The reason why I used this method is that I used the cache here to reduce the number of times I accessed the database, the most frequently accessed data is converted into objects and stored in the cache. To tell the truth, I only heard about and understand the principle, but have not implemented it. I will not talk about it here.

The In Memory Caching method officially provided by Microsoft has a Microsoft standard example. The GitHub address is here

The example is implemented using middleware. After some learning, the cache is implemented using the method mentioned in the example through middleware, but how to use the Controller becomes a challenge, or maybe I do not know much about middleware! I don't know what to do! Without patience, I carefully studied the code and found that the cache calling (including setting and retrieval) in the middleware is actually implemented only in the following code:

1 if (! _ MemoryCache. tryGetValue (cacheKey, out greeting) 2 {3 // fetch the value from the source 4 greeting = _ greetingService. greet ("world"); 5 6 // store in the cache 7 _ memoryCache. set (cacheKey, greeting, 8 new MemoryCacheEntryOptions () 9. setAbsoluteExpiration (TimeSpan. fromMinutes (1); 10 _ logger. logInformation ($ "{cacheKey} updated from source. "); 11} 12 else13 {14 _ logger. logInformation ($ "{cacheKey} retrieved from cache. "); 15}View Code

That is, the Section _ memoryCache. TryGetValue (cacheKey, out greeting) is used to retrieve the cached content from the cache, while the Section _ memoryCache. Set (cacheKey, greeting, new MemoryCacheEntryOptions ()
. SetAbsoluteExpiration (TimeSpan. FromMinutes (1); this method call places data in the cache!

After knowing this, I started to transform my program:

1. Create the IAdminTreeService. cs interface class:

Public interface IAdminTreeService {// <summary> // All node data tree /// </summary> AdminUserTree GetAllTreeData {get ;}}

2. create the service AdminTreeServices. cs is used to retrieve management menu data from the database. The implementation of this method using the service method still draws on the implementation of the official example. This implementation is justified. Let's figure it out. At least we have to use unified interfaces. Code is no longer required:

1 public class AdminTreeServices: IAdminTreeService 2 {3 /// <summary> 4 // EF data access configuration 5 /// </summary> 6 private readonly ApplicationDbContext _ basecontext; 7 8 public AdminTreeServices (ApplicationDbContext context) 9 {10 _ basecontext = context; 11} 12 13 // <summary> 14 // create an infinitus node tree-management menu 15 /// </summary> 16 /// <returns> </returns> 17 public AdminUserTree GetAllTreeData 18 {19 get 20 {21 Admi NUserTree result = new AdminUserTree (); 22 // initialize a node as the root node 23 result. nodeID = 0; 24 result. text = "Administrator menu"; 25 result. url = ""; 26 result. parentID =-1; 27 result. location = ""; 28 result. orderID = 0; 29 result. comment = "database source"; 30 result. imageUrl = ""; 31 result. permissionID = 0; 32 result. level = 0; 33 result. childNumberl = 0; 34 // pass the root node to the recursive method to create a subnode 35 result. childNode = BuildMenuTree (result,-1 ); 36 return result; 37 38} 39 40} 41 42 43 // <summary> 44 // recursive subnode Creation Method 45 /// </summary> 46 // <param name = "node"> parent node for which you want to allocate child nodes </param> 47 // <param name = "levelID"> hierarchical relationship </param> 48 /// <returns> </returns> 49 protected List <AdminUserTree> BuildMenuTree (AdminUserTree node, int levelID) 50 {51 var listtree = _ basecontext. admintree; 52 53 // retrieve all the subnode conditions of the node from the database: m. parentID = node. nodeID 54 Lis T <AdminUserTree> lt = listtree. where (m => m. parentID = node. nodeID) 55. select (m => new AdminUserTree () 56 {57 NodeID = m. nodeID 58, 59 Text = m. text 60, 61 Url = m. url 62, 63 ParentID = m. parentID 64, 65 Location = m. location 66, 67 OrderID = m. orderID 68, 69 Comment = m. comment 70, 71 ImageUrl = m. imageUrl 72, 73 PermissionID = m. permissionID 74}) 75. toList (); 76 77 if (lt! = Null) 78 {79 // node depth 80 node. level = levelID + 1; 81 // Number of subnodes, so that 82 nodes can be called during recursive output at the front end. childNumberl = lt. count; 83 for (int I = 0; I <lt. count; I ++) 84 {85 // recursively call to create a subnode 86 lt [I]. childNode = BuildMenuTree (lt [I], node. level); 87} 88 return lt; 89 90} 91 else 92 {93 return null; 94} 95 96 97 98 99} 100 101}AdminTreeServices

3. admin page base class AdminBase. cs:

1 public class AdminBase: Controller 2 {3 /// <summary> 4 // EF data access configuration 5 /// </summary> 6 private readonly ApplicationDbContext _ basecontext; 7 private readonly IAdminTreeService _ adminTreeService; 8 private readonly ILogger <AdminUserTree> _ logger; 9 private readonly IMemoryCache _ memoryCache; 10 11 12 /// <summary> 13 // The management menu here is the base, declared as the attribute so that 14 /// can be used in the Controller </summary> 15 public AdminUserTree leftMenu {Get; set;} 16 17 18 public AdminBase (ApplicationDbContext context, 19 IMemoryCache memoryCache, 20 ILogger <AdminUserTree> logger, 21 IAdminTreeService adminTreeService) 22 {23 _ basecontext = context; 24 // initialize the infinitus Classification Management menu 25 _ logger = logger; 26 _ adminTreeService = adminTreeService; 27 _ memoryCache = memoryCache; 28 leftMenu = GetAdminTreeByCache (); 29} 30 31 // <summary> 32 // read node tree 33 from the cache // </summary> 34 /// <Param name = "httpContext"> </param> 35 // <returns> </returns> 36 public AdminUserTree GetAdminTreeByCache () 37 {38 string cacheKey = "AdminTree-Base"; 39 AdminUserTree adminTree; 40 41 // a method for obtaining cached content 42 // greeting = _ memoryCache. get (cacheKey) as string; 43 44 // another way to Get cache content, 45 // alternately, TryGet returns true if the cache entry was found46 if (! _ MemoryCache. TryGetValue (cacheKey, out adminTree) 47 {48 // This content does not exist in the cache and is obtained from the data interface by accessing the database. 49 adminTree = _ adminTreeService. getAllTreeData; 50 51 // The absolute expiration time method. It expires after 3 minutes when the cache is set. 52 // _ memoryCache. set (cacheKey, adminTree, 53 // new MemoryCacheEntryOptions () 54 //. setAbsoluteExpiration (TimeSpan. fromMinutes (3); 55 // method of relative expiration time, which expires 3 minutes after the last call. set (cacheKey, adminTree, 57 new MemoryCacheEntryOptions () 58. setSlidingExpiration (TimeSpan. fromMinutes (3); 59 // logs 60_logger. logInformation ($ "{c AcheKey} From Data. "+ DateTime. now. addMinutes (3 ). toString (); 61} 62 else63 {64 // record the log, which indicates that the current data is read from the cache. 65 _ logger. LogInformation ($ "{cacheKey} From Cacha." + DateTime. Now. ToString (); 66} 67 68 return adminTree; 69 70} 71}AdminBase

4. Do not forget to add the following code to Startup. cs:

1 public void ConfigureServices(IServiceCollection services)2         {3             …………4              services.AddMemoryCache();5 6              services.AddTransient<IAdminTreeService, AdminTreeServices>();7 }

 

 

Here, data is basically read through the cache! As the implementation in Controller has not changed, please refer to my previous article:

C # infinitus Classification Tree-create-sort-read using Asp. Net Core + EF

In order to facilitate reading, you can repeat the menu Node Code:

1 /// <summary> 2 /// infinitus node class 3 /// </summary> 4 public class AdminUserTree 5 {6 /// <summary> 7 // Node information 8 /// </summary> 9 public int NodeID {get; set;} 10 /// <summary> 11 /// node name 12 /// </summary> 13 public string Text {get; set ;} 14 /// <summary> 15 /// parent node ID16 /// </summary> 17 public int ParentID {get; set ;} 18 /// <summary> 19 /// corresponding link address 20 /// </summary> 21 public string Url {get; set;} 22 p Ublic int? PermissionID {get; set;} 23 public int? OrderID {get; set;} 24 public string Location {get; set;} 25 public string Comment {get; set;} 26 public string ImageUrl {get; set ;} 27 /// <summary> 28 // Level 29 /// </summary> 30 public int Level {get; set ;} 31 /// <summary> 32 // Number of subnodes (important) 33 // </summary> 34 public int ChildNumberl {get; set ;} 35 36 /// <summary> 37 // What is the usage of subnode (the subnode is a List? 38 // </summary> 39 public List <AdminUserTree> ChildNode {get; set;} 40}View Code

Finally, release the runtime log:

First visit:

There are a lot of database access statements, the log prompts the data source and database

Access again:

Here is the content directly read from the cache!

Well, today's content will be written here.

According to the previous plan, the next step is to study the user and permission content. This time I plan to study ASP. NET Identity authentication and role-based authorization. There are a lot of related information on the Internet, but I still don't understand how to integrate with my actual project. It may take several days!

 

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.