Using Redis cache for ASP. NET performance optimization (Getting started)

Source: Internet
Author: User

1: Optimizing Ideas for using Redis cache

Redis uses a lot of scenarios, only the one scenario I used:

1.1 For a large amount of data read, in order to alleviate the pressure of the database, some infrequently changing and frequently read data into the Redis cache

The general idea is as follows: Execute a query

1.2 First determine if the cache exists, if any exist directly from the Redis cache.

1.3 If the Redis cache does not exist, read the database data in real time and write the cache at the same time (and set the cache to expire).

1.4 Disadvantage, if the data of the database is modified directly without updating the cache, the Redis cache that will cause the read in the time of cache failure is the wrong data.

2:redis-Fool installation

2.1 Double-click Execute Redis-2.4.6-setup-64-bit.exe Program (: https://github.com/dmajkic/redis/downloads)

2.2 You can set this service as a Windows system service:

2.3 Test whether the installation was successful:

Go back to the Redis folder and find the Redis-cli.exe file, which is the Redis client program. Open, enter:

Set Test 123

That is, you insert a key of Test,value 123 in the Redis and continue typing: get test

Gets the value of the saved data 123.

If you want to know how many data are saved in Redis, you can use: Keys * to query:

3:asp.net Simple example of using Redis cache

3.1 Testing the structure of the demo

3.2 Adding references

3.3 Writing parameters to the configuration file

<appSettings> <add key="writeserverlist"Value="127.0.0.1:6379"/> <add key="readserverlist"Value="127.0.0.1:6379"/> <add key="maxwritepoolsize"Value=" -"/> <add key="maxreadpoolsize"Value=" -"/> <add key="AutoStart"Value="true"/> <add key="Localcachetime"Value="1800"/> <add key="Recordelog"Value="false"/> </appSettings>

3.4 Reading the configuration file parameter class

  Public classRedisconfiginfo { Public Static stringWriteserverlist = configurationmanager.appsettings["writeserverlist"];  Public Static stringReadserverlist = configurationmanager.appsettings["readserverlist"];  Public Static intMaxwritepoolsize = Convert.ToInt32 (configurationmanager.appsettings["maxwritepoolsize"]);  Public Static intMaxreadpoolsize = Convert.ToInt32 (configurationmanager.appsettings["maxreadpoolsize"]);  Public Static intLocalcachetime = Convert.ToInt32 (configurationmanager.appsettings["Localcachetime"]);  Public Static BOOLAutoStart = configurationmanager.appsettings["AutoStart"]. Equals ("true") ?true:false; }

3.5 Connecting to Redis, and some other operating classes

 Public classRedismanager {Private StaticPooledredisclientmanager PRCM; /// <summary>        ///Create a linked Pool management object/// </summary>        Private Static voidCreatemanager () {string[] writeserverlist = splitstring (Redisconfiginfo.writeserverlist,","); string[] readserverlist = splitstring (Redisconfiginfo.readserverlist,","); PRCM=NewPooledredisclientmanager (readserverlist, Writeserverlist,NewRedisclientmanagerconfig {maxwritepoolsize=redisconfiginfo.maxwritepoolsize, Maxreadpoolsize=redisconfiginfo.maxreadpoolsize, AutoStart=Redisconfiginfo.autostart,}); }        Private Static string[] splitstring (stringStrsource,stringsplit) {            returnStrsource.split (Split.        ToArray ()); }        /// <summary>        ///Client Cache Action Object/// </summary>         Public Staticiredisclient getclient () {if(PRCM = =NULL) Createmanager (); returnPRCM.        Getclient (); }        /// <summary>        ///cache default 24-hour expiration/// </summary>         Public StaticTimeSpan Expiresin = timespan.fromhours ( -); /// <summary>        ///set a key-value pair that expires 24 hours by default/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "key" ></param>        /// <param name= "value" ></param>        /// <param name= "redisclient" ></param>        /// <returns></returns>         Public Static BOOLSet<t> (stringkey, T value, Iredisclient redisclient) {            returnRedisclient.set<t>(key, value, Expiresin); }        /// <summary>        ///inserting a class of data into a list/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "key" >It's usually biaodiguid .</param>        /// <param name= "item" ></param>        /// <param name= "redisclient" ></param>         Public Static voidAdd2list<t> (stringkey, T item, Iredisclient redisclient) {            varRedis = redisclient.as<t>(); varList =Redis.            Lists[getlistkey (key)]; List.        ADD (item); }        /// <summary>        ///Gets a list/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "key" ></param>        /// <param name= "redisclient" ></param>        /// <returns></returns>         Public StaticIredislist<t> getlist<t> (stringkey, Iredisclient redisclient) {            varRedis = redisclient.as<t>(); returnRedis.        Lists[getlistkey (key)]; }         Public Static stringGetlistkey (stringKeystringprefix =NULL)        {            if(string. IsNullOrEmpty (prefix)) {return "urn:"+key; }            Else            {                return "urn:"+ prefix +":"+key; }        }    }
View Code

3.6 test page front and back code

<form id="Form1"runat="Server"> <div> <asp:label runat="Server"Id="lbtest"></asp:Label> <asp:button runat="Server"ID ="BTN1"onclick="Btn1_click"text="Get test Data"/> </div> </form>
 protected voidBtn1_click (Objectsender, EventArgs e) {            stringUserName; //Read data, read from the database and then write to Redis if the cache exists directly from the cache            using(varRedisclient =redismanager.getclient ()) {UserName= redisclient.get<string> ("userinfo_123"); if(string. IsNullOrEmpty (UserName))//Initializing the cache                {                    //TODO fetches data from the database and writes to the cacheUserName ="Zhang San"; Redisclient.set<string> ("userinfo_123", UserName, DateTime.Now.AddSeconds (Ten)); Lbtest. Text="Database data:"+"Zhang San"; return; } lbtest. Text="Redis Cache data:"+UserName; }        }

Test result diagram

Data does not exist in the first access cache, gets data and writes to the cache, and sets a validity period of 10 seconds

Access to read cache data in 10 seconds

Using Redis cache for ASP. NET performance optimization (Getting started)

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.