Use delegation to implement your own data cache warehouse

Source: Internet
Author: User

Demo source code

Background

I wanted to talk about the background of this article, and later I found that the native word is poor. Therefore, in this topic, we use delegation to implement a global data cache warehouse.

This class Library receives four parameters: 1. the Data Type of the data to be stored; 2. the method for obtaining the data to be stored; 3. The expiration time; 4. The unique key for reading the data

This class library can be used to obtain data based on the key. The data is obtained by executing the data acquisition method that you pass in. When the time for obtaining data expires, will re-execute the data retrieval method to update the data!

Recommended usage: 1. At the beginning of the application, Initialize all the data to be cached and manage all the keys in a unified manner. This avoids unnecessary confusion.

2. You can directly obtain data from the key where the application needs to use it. This avoids repeated code writing on each page and improves application efficiency.

Implementation

Step 1: Define a standard data structure for the data to be stored:

  

/// <Summary> /// data structure to be stored /// </Summary> /// <typeparam name = "T"> data type to be stored (string int ..) </typeparam> Public sealed class storeddatainfo <t >{/// <summary> /// stored data /// </Summary> Public t data {Get; set ;} /// <summary> /// method for obtaining the data to be stored /// </Summary> Public func <t> getdatamethod {Get; set ;} /// <summary> /// data expiration time /// </Summary> Public int timeofduration {Get; set ;} /// <summary >/// data last updated // </Summary> Public datetime lastmodifytime {Get; Set ;}}

The above code is clear at a glance. You can understand it without much further explanation.

Step 2: we need a list to store the required data, because we store a lot of data.

  

// Store all data /// <summary> /// store all data /// </Summary> Private Static readonly dictionary <string, storeddatainfo <t> entirestoreddata = new dictionary <string, storeddatainfo <t> ();

Step 3: Initialize the data

// Initialize the data item // <summary> // initialize the data item // </Summary> /// <Param name = "key"> </param> /// <Param name = "storeddata"> </param> Private Static string initstoreddataitem (string key, storeddatainfo <t> storeddata) {lock (lockobj) {If (entirestoreddata. containskey (key) {return "key:" + key + "already exists";} entirestoreddata. add (Key, storeddata);} return "";}

Step 4: obtain data items based on the key

// Obtain the data item of the specified key /// <summary> /// obtain the data item of the specified key /// </Summary> /// <Param name = "key"> </param> /// <Param name = "isforcedrefresh"> force update </param> /// <returns> </returns> Public static t getdata (string key, bool isforcedrefresh = false) {// key if (! Haskey (key) {# region string currkeys = ""; string currttype = ""; if (entirestoreddata. any () {currkeys = string. join (",", entirestoreddata. keys. toarray (); var v = entirestoreddata. first (). value. data; currttype = v. getType (). tostring ();} Throw new exception (string. format ("no specified key: {0}, current pool contains key set {1}, current pool type: {2}", key, currkeys, currttype )); # endregion} // obtain value storeddatainfo based on the key <t> SDI = entire Storeddata [Key]; // determines whether the expiration date is int timeofduration = SDI. timeofduration; datetime lastmodifytime = SDI. lastmodifytime; If (! Isforcedrefresh & datetime. now. addminutes (-timeofduration) <= lastmodifytime) return SDI. data; // update the data SDI again. data = SDI. getdatamethod (); SDI. lastmodifytime = datetime. now; return SDI. data ;}

Use

Static void main (string [] ARGs) {# region data cache repository test // key const string key = "getcurrdatekey"; // initialize the repository DataWarehouse <string>. initdataitem (Key, getcurrdate, 1); // obtain the value of Console Based on the key. writeline (DataWarehouse <string>. getdata (key); // sleep waiting for expiration thread. sleep (1000*61); // obtain the value console again based on the key. writeline (DataWarehouse <string>. getdata (key); console. readline (); # endregion} // <summary> // obtain the time /// </Summary> /// <returns> </returns> Private Static string getcurrdate () {return datetime. now. tostring ();}

The above is a very small test to store a string value of the current time and set the expiration time to 1 minute. The result is very obvious.

  

 

Use delegation to implement your own data cache warehouse

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.