Use Redis cache for asp.net performance optimization (Getting Started), asp. netredis

Source: Internet
Author: User

Use Redis cache for asp.net performance optimization (Getting Started), asp. netredis

1: optimization ideas for using Redis Cache

There are many application scenarios for redis. Let's just talk about one of my scenarios:

1.1 for a large amount of data reading, in order to relieve the pressure on the database, some infrequently changed and frequently read data is stored in the redis Cache

The general idea is as follows: execute a query

1.2 first, determine whether the cache exists. If the cache exists, obtain it directly from the Redis cache.

1.3 if the Redis cache does not exist, read the database data in real time and write the data to the cache (and set the cache expiration time ).

1.4 disadvantages: if the database data is directly modified without updating the cache, the read Redis cache will be wrong during the cache expiration time.

2: Redis Installation

2.1double 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 is successful:

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

Set test 123

That is, a piece of data with the key as test and the value as 123 is inserted in Redis. Continue to input: get test

123 of the data saved by value is obtained.

If you want to know how many data records are stored in Redis, you can use: keys * to query:

3: simple example of asp.net using Redis Cache

3.1 Test the Demo Structure

3.2 add reference

3.3 write 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="60" /> <add key="MaxReadPoolSize" value="60" /> <add key="AutoStart" value="true" /> <add key="LocalCacheTime" value="1800" /> <add key="RecordeLog" value="false" /> </appSettings>

3.4 read configuration file Parameters

 public class RedisConfigInfo {  public static string WriteServerList = ConfigurationManager.AppSettings["WriteServerList"];  public static string ReadServerList = ConfigurationManager.AppSettings["ReadServerList"];  public static int MaxWritePoolSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxWritePoolSize"]);  public static int MaxReadPoolSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxReadPoolSize"]);  public static int LocalCacheTime = Convert.ToInt32(ConfigurationManager.AppSettings["LocalCacheTime"]);  public static bool AutoStart = ConfigurationManager.AppSettings["AutoStart"].Equals("true") ? true : false; }

3.5 connect to Redis and some other operations

Public class RedisManager {private static PooledRedisClientManager prcm; // <summary> // create a link pool management object // </summary> private static void CreateManager () {string [] writeServerList = SplitString (RedisConfigInfo. writeServerList, ","); string [] readServerList = SplitString (RedisConfigInfo. readServerList, ","); prcm = new PooledRedisClientManager (readServerList, writeServerList, new RedisClientManagerConfig {MaxWritePoolSize = RedisConfigInfo. maxWritePoolSize, MaxReadPoolSize = RedisConfigInfo. maxReadPoolSize, AutoStart = RedisConfigInfo. autoStart,});} private static string [] SplitString (string strSource, string split) {return strSource. split (split. toArray ();} // <summary> // Client Cache operation object // </summary> public static IRedisClient GetClient () {if (prcm = null) createManager (); return prcm. getClient () ;}/// <summary> /// cache expires 24 hours by default /// </summary> public static TimeSpan expiresIn = TimeSpan. fromHours (24); // <summary> // you can specify a key-value pair, the default value is 24 hours. // </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "key"> </param> /// <param name = "value"> </param> /// <param name = "redisClient"> </param> /// <returns> </returns> public static bool Set <T> (string key, T value, IRedisClient redisClient) {return redisClient. set <T> (key, value, expiresIn );} /// <summary> /// insert certain types of data into the list /// </summary> /// <typeparam name = "T"> </typeparam> // /<param name = "key"> generally BiaoDiGuid </param> // <param name = "item"> </param> // <param name = "redisClient "> </param> public static void Add2List <T> (string key, T item, IRedisClient redisClient) {var redis = redisClient. as <T> (); var list = redis. lists [GetListKey (key)]; list. add (item );} /// <summary> /// obtain a list /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "key"> </param> /// <param name = "redisClient"> </param> /// <returns> </returns> public static IRedisList <T> getList <T> (string key, IRedisClient redisClient) {var redis = redisClient. as <T> (); return redis. lists [GetListKey (key)];} public static string GetListKey (string key, string prefix = null) {if (string. isNullOrEmpty (prefix) {return "urn:" + key;} else {return "urn:" + prefix + ":" + key ;}}}

3.6 front and back-end code of the test page

<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 void btn1_Click (object sender, EventArgs e) {string UserName; // read data. If the cache exists, it is directly read from the cache, otherwise, read data from the database and write data to redis using (var redisClient = RedisManager. getClient () {UserName = redisClient. get <string> ("UserInfo_123"); if (string. isNullOrEmpty (UserName) // initialize the cache {// TODO obtains data from the database and writes it to the cache UserName = "Zhang San"; redisClient. set <string> ("UserInfo_123", UserName, DateTime. now. addSeconds (10); lbtest. text = "database data:" + "Michael"; return;} lbtest. text = "Redis cache data:" + UserName ;}}

Test result Diagram

The data in the cache does not exist during the first access. The data is obtained and written to the cache, And the validity period is set to 10 seconds.

Access and read cache data again within 10 seconds

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.