Use memcached to Improve the Performance of. NET applications)

Source: Internet
Author: User

When an application is running, there will always be data that needs to be accessed frequently and does not change frequently. If the data needs to be read from the database or external file system every time you obtain the data, the performance will certainly be affected.
Therefore, the common practice is to cache this part of the data, as long as the data does not change, the performance will be greatly improved if the data is directly obtained from the memory. In. net
A cache class can implement these functions. In ASP. NET, you can use the cache attribute of the httpcontext object or the cache of the page object.
To obtain the instance of this class.
In most cases, we can use the cache class to improve ASP. NET performance, but the cache class also has some shortcomings. For example, we cannot specify the memory occupied by the cache class
In addition, the data cached in the cache cannot be directly accessed by applications on another machine. Therefore, this article proposes another data cache solution, that is, using the distributed cache. Distributed cache
It is characteristic that the cached data does not need to be on the same machine as the application, thus greatly enhancing the reusability of the cached data. This article describes how to use memcache for Distributed easing in. NET applications.
Save.
Introduction to memcached
Memcached is Brad fitzpatric, danga interactive under livejournal.
A software first developed. In common applications, we store data in the database, and query the data from the database every time we need it. If many users of the application have a large number of concurrent requests
When accessing the database, the response time of the application will be increased, and memcached can effectively solve this problem. Memcached is a high-performance distributed memory cache service.
. The general purpose is to reduce the number of database accesses by caching database query results, so as to speed up dynamic web applications and improve scalability. Like a well-known Facebook website
Memcached is used. Zhou Gong will later provide the 32-bit and 64-bit memcached programs on the Windows platform.
To improve performance, data in memcached is stored in the built-in storage space of memcached. Because when memcached is restarted, all data is lost.
The general solution is to save the data in the database. Each time you request data, check whether there is a cache in memcached. If yes, retrieve the data directly from the cache. If no, retrieve the data from the database.
The data is returned to the application and the requested data is cached in memcached. In this way, the next request for the same data can be directly read from memcached without the need to query the database;
Once the data is updated, both the database and memcached are updated.
Memcached is a command line window program that can be started in the command line window or encapsulated in system services. When starting memcached, you must provide some required parameters to specify
The port number and the maximum memory size that memcached listens to during running. If the cached data exceeds the specified memory size, memcached will follow the LRU (least
Recently
Used) the algorithm automatically "deletes" unused caches (marked as invalid). The memory occupied by the new cached data can be used to mark the invalid data, so that you do not have to worry about memcached.
Exceeds the specified memory. In addition, to improve performance, memcached does not delete cached data from the physical memory after the cached data expires. Instead, it only checks whether the cached data has been retrieved and modified.
After the validity period.
Currently, memcached is available on multiple platforms, such as Linux, FreeBSD, Solaris (memcached 1.2.5 or later), Mac OS X, and Windows. On Windows, there are also 32-bit and 64-bit versions.
Memcached has a set of protocols that allow you to access memcached data and view the status of memcached. Many programming languages use this Protocol to operate memcached, for example, PHP, Java, C, C ++, and C.
Get the memcached version of the corresponding platform to run memcached. Here, we only use 32-bit memcached on Windows as an example.
Run memcached:
Memcached.exe-P 11121-M 64
The above command is to run memcached and specify that its listening port is 11121 (this is its default port, which can be another port greater than 1024, because the default value is already set for ports smaller than 1024), and the maximum memory usage is 64 mb. If Windows Firewall is enabled, open this port on the firewall.
You can run the following command line during program debugging:
Memcached.exe-P 11121-M 64-VV
The following result is displayed:
Slab Class 1: Chunk Size 88 perslab 11915
Slab Class 2: Chunk Size 112 perslab 9362
Slab Class 3: Chunk Size 144 perslab 7281
Slab Class 4: Chunk Size 184 perslab 5698
Slab Class 5: Chunk Size 232 perslab 4519
Slab Class 6: Chunk Size 296 perslab 3542
Slab Class 7: Chunk Size 376 perslab 2788
Slab Class 8: Chunk Size 472 perslab 2221
Slab Class 9: Chunk Size 592 perslab 1771
Slab class 10: Chunk Size 744 perslab 1409
Slab class 11: Chunk Size 936 perslab 1120
Slab Class 12: Chunk Size 1176 perslab 891
Slab class 13: Chunk Size 1472 perslab 712
Slab class 14: Chunk Size 1840 perslab 569
Slab class 15: Chunk Size 2304 perslab 455
Slab Class 16: Chunk Size 2880 perslab 364
Slab Class 17: Chunk Size 3600 perslab 291
Slab class 18: Chunk Size 4504 perslab 232
Slab class 19: Chunk Size 5632 perslab 186
Slab class 20: Chunk Size 7040 perslab 148
Slab Class 21: Chunk Size 8800 perslab 119
Slab Class 22: Chunk Size 11000 perslab 95
Slab Class 23: Chunk Size 13752 perslab 76
Slab class 24: Chunk Size 17192 perslab 60
Slab Class 25: Chunk Size 21496 perslab 48
Slab Class 26: Chunk Size 26872 perslab 39
Slab class 27: Chunk Size 33592 perslab 31
Slab Class 28: Chunk Size 41992 perslab 24
Slab class 29: Chunk Size 52496 perslab 19
Slab class 30: Chunk Size 65624 perslab 15
Slab class 31: Chunk Size 82032 perslab 12
Slab class 32: Chunk Size 102544 perslab 10
Slab Class 33: Chunk Size 128184 perslab 8
Slab Class 34: Chunk Size 160232 perslab 6
Slab class 35: Chunk Size 200296 perslab 5
Slab class 36: Chunk Size 250376 perslab 4
Slab Class 37: Chunk Size 312976 perslab 3
Slab Class 38: Chunk Size 391224 perslab 2
Slab class 39: Chunk Size 489032 perslab 2
<96 server listening
<112 server listening
<116 send buffer was 8192, now 268435456
<116 server listening (UDP)
You can also use Telnet to view and operate memcached on the client, provided that both the server and client support the Telnet protocol, which is not supported by windows7 and windows2008 by default, it must be installed and enabled in the control panel.
First open the control panel, and then click "enable or disable windows", as shown in:
 

After you click "enable or disable windows", you will see the status of the features enabled by the current system. Select to enable the telnet server or client functions based on the current machine, as shown in:
 

 
After the above operations, you can remotely view the memcached status or operate memcached on the client. The following command is used to connect to memcached:
Telnet local host 11121
After the connection, a command line window appears. In this command line window, enter "stats" to view the current memcached status, as shown below:
Stat PID 852
Statuptime 1399
Stat time 1300979378
Stat version 1.2.5
Stat pointer_size 32
Stat curr_items 0
Stat total_items 0
Stat bytes 0
Stat curr_connections 3
Stat total_connections 5
Stat connection_structures 4
Stat performance_get 0
Stat performance_set 0
Stat get_hits 0
Stat get_misses 0
Stat evictions 0
Stat bytes_read 23
Stat bytes_written 415
Stat limit_maxbytes 67108864
Stat threads 1
End
With this data, we can understand the status of memcached.
The data represents the following meanings:
PID: 32u, server process ID.
Uptime: 32u, server running time, in seconds.
Time: 32u, the current UNIX time of the server.
Version: string, the server version number.
Curr_items: 32u, number of contents currently stored by the server current number of items stored by the server
Total_items: 32u, total number of contents stored since the server was started.
Bytes: 64u, the number of bytes occupied by the server's current storage content.
Curr_connections: 32u, number of connections.
Total_connections: 32u, total number of connections received since the server was running.
Connection_structures: 32u, number of connection structures allocated by the server.
Cmd_get: 32u, total number of retrieved requests.
Pai_set: 32u, total number of stored requests.
Get_hits: 32u, the total number of successful requests.
Get_misses: 32u, the total number of failed requests.
Bytes_read: 64u, the total number of bytes that the server reads from the network.
Bytes_written: 64u, the total number of bytes sent by the server to the network.
Limit_maxbytes: 32u, total number of bytes that can be used by the server during storage.
In the above description, 32u and 64u indicate 32-bit and 64-bit unsigned integers, and string indicates string type data.

Apply memcached in. net
There are many. Net version memcached client programs. Here, we use enyim memcached, which can download the latest version at https://github.com/enyim/enyimmemcached.
To use memcached in a project, you must add an application for enyim. caching. dll. In addition, we may need to configure memcached information in the config file (you can also specify it in the program code, but it is not flexible). The following is an example of configuration in the config file:

    <?xml version="1.0" encoding="utf-8" ?>     <configuration>       <configSections>         <sectionGroup name="enyim.com">           <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />         </sectionGroup>       </configSections>       <enyim.com protocol="Binary">         <memcached>           <servers>             <add address="localhost" port="11121" />             <!--<add address="localhost" port="11131" />             <add address="localhost" port="11141" />             <add address="localhost" port="11151" />-->           </servers>           <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />         </memcached>       </enyim.com>     </configuration> 

If we have configured multiple memcached instances, you can add multiple memcached instance configurations under the <servers> node as described above.
It should be noted that if we need to add a custom data type to memcached, we need to add the [serializable] flag for this data type.
The following is an example of enyim memcached:

Using system; using system. collections. generic; using system. LINQ; using system. text; using enyim. caching; using enyim. caching. memcached;/** Author: Zhou Gong (zhoufoxcn) * Date: 2011-03-24 * Source: http://blog.csdn.net/zhoufoxcn or http://zhoufoxcn.blog.51cto.com * copyright Description: This article can be used for non-commercial purposes while retaining the source of the original, zhou Gong does not provide any guarantee or commitment for this. **/Namespace memcachedmonitor {[serializable] public class person {public int userid {Get; set;} Public String username {Get; Set ;}} public class memcacheddemo {Private Static memcachedclient client = new memcachedclient ("enyim.com/memcached"); Public void setdemo () {person = new person {userid = 1, username = "Li Gang "}; // for storage without expiration time, memcached determines the expiration Policy bool success = client based on LRU. store (Storemode. add, person. username, person); // cache with expiration time // bool success = client. store (storemode. add, person. username, person, datetime. now. addminutes (10); console. writeline ("result of storing [{0}]: {1}", person. username, success);} public void getdemo () {person = client. get <person> ("Li Gang"); If (person! = NULL) {console. writeline ("retrieve [{0}] results -- userid: {1}, Username: {2}", "Li Gang", person. userid, person. username);} else {console. writeline ("retrieving [{0}] failed! "," Li Gang ") ;}} public void multigetdemo () {list <string> personnamelist = new list <string> (); For (INT I = 0; I <10; I ++) {personnamelist. add ("Li Gang 00" + I);} // obtain all the specified idictionary <string, Object> resultlist = client. get (personnamelist); person; foreach (keyvaluepair <string, Object> item in resultlist) {person = item. value as person; if (person! = NULL) {console. writeline ("retrieve [{0}] results -- userid: {1}, Username: {2}", "Li Gang", person. userid, person. username);} else {console. writeline ("retrieving [{0}] failed! "," Li Gang ");}}}}}

Note: If you need to retrieve multiple cached data from memcached at a time, you can refer to the multigetdemo () method. In this way, you can retrieve all the data in one network communication.
To reduce the network connection time. In addition, the memcached client can use the text or binary protocol. After more than 10 million tests per week, the performance of the binary protocol is slightly higher.
Use the text protocol. In the preceding config file, Zhou Gong configured to use the binary protocol.
In summary, the use of distributed cache such as memcached can greatly improve the performance of applications. After a weekly public test, the correct use of memcached can replace the number of concurrent workers of a single server from
20 is increased to around 1000, that is, increased by 50 times, which is a very objective improvement! The usage of memcached is not described in this article.
You can refer to other related materials on your own.

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.