Memcached in ASP. NET usage

Source: Internet
Author: User
Tags log4net

Now some. NET developers began to abandon the built-in cache mechanism of ASP. NET, instead of using memcached, a distributed memory cache system, which was initially developed for the livejournal website by danga interactive.

A basic problem of caching is how to process outdated data. When running on a separate web server, you can easily clear a cache that has been confirmed to be changed. Unfortunately, ASP. NET does not have a good way to support multiple servers. The cache on each server knows nothing about changes to other caches.

ASP. NET allows you to invalidate a cache by using a Trigger Based on the file system and database table. However, this also has problems. For example, database Triggers require expensive Round Robin and trigger lengthy programming. However, we still have other options.

Unlike the built-in cache mechanism of ASP. NET, memcached is a distributed cache system. Any web server can update or delete a cache item, and all other servers can automatically obtain the updated content the next time they access these cache items. This is achieved by storing these cache items on one or more cache servers. Each cache item is assigned to a server based on the hash value of Its keywords. Content from china webmaster Information Network (www.chinahtml.com)

On the surface, memcached's APIs for ASP. NET are the same as those for built-in APIs. This allows developers to easily switch to memcached, simply by searching and replacing the code.

However, it is not enough to make it run. If you want to use it correctly on a large Web farms website, you need to pay attention to some issues. Richard Jones wrote: The content is from www.chinahtml.com, a Chinese webmaster)

When many nodes are added, the usefulness of the get_multi function is reduced-this may be due to the need to access almost all memcached instances on a separate page. I read Facebook somewhere (Translator's note: today's popular campus social networking sites) splitting their memcached clusters to Improve the Performance of get_multi (for example, all user data is stored on a subset node named MC ). Can someone tell me how this works?

A recommended solution is to generate a hash key value based on the key words of the cache item. This allows developers to store all the cache items required on a given page on the same server as much as possible. It is a pity that the hash key is generated based on the data storage place rather than the key of the cache item itself, which is easy to produce errors and needs to be carefully implemented (this algorithm ).

 

Memcached in ASP. NET

I. Preparation
You need the following software:
Vs. Net (05/08)
Sqlserver
Memcached server and client class libraries (open-source software, download it)
The client class library includes the following dll:
Memcached. clientlibrary. dll
Icsharpcode. sharpziplib. dll
Log4net. dll
2. Install the memcached Server
Copy memcached.exe to any directory, such as C:. On the command line, enter:
Memcached.exe-D install
Memcached will act as a Service resident system memory
3. Create an ASP. NET Project
Create an ASP. netweb project named mmcweb and add references to the client class libraries mentioned above.
Iv. Configuration
Memcached uses log4net, so we first configure log4net
Find the configsections node in Web. config and add the following content:
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net"/>

Add the following content to the configsections node:
<Log4net>
<Appender name = "rollinglogfileappender" type = "log4net. appender. rollingfileappender">
<Param name = "file" value = "logfiles/"/>
<Param name = "appendtofile" value = "true"/>
<Param name = "maxsizerollbackups" value = "10"/>
<Param name = "staticlogfilename" value = "false"/>
<Param name = "datepattern" value = "yyyy-mm-dd&quot;.txt & quot;"/>
<Param name = "rollingstyle" value = "date"/>
<Layout type = "log4net. layout. patternlayout">
<Param name = "conversionpattern" value = "% d {yyyy-mm-dd hh: mm: SS} [% thread] %-5 level % logger % NDC-% message % newline "/>
</Layout>
</Appender>
<Appender name = "leleappender" type = "log4net. appender. consoleappender">
<Layout type = "log4net. layout. patternlayout">
<Param name = "conversionpattern" value = "% d {yyyy-mm-dd hh: mm: SS} [% thread] %-5 level % logger % NDC-% message % newline "/>
</Layout>
</Appender>
<Root>
<Level value = "all"/>
<Appender-ref = "rollinglogfileappender"/>
<Appender-ref = "leleappender"/>
</Root>
<Logger name = "memcached. clientlibrary">
<Level value = "Warn"/>

</Logger>
</Log4net>
Start debugging. If no configuration error prompt is displayed and logfiles is in the directory of the website, log4net configuration is successful.

5. initialize sockiopool
What is sockiopool? Sockiopool is a socket connection pool provided by the memcached client. Generally speaking, it is an object for exchanging data with the memcached server. Sockiopool can be initialized once when the application is started. I put this job in the application_start method of Global. asax. CS.
Char [] separator = {','};
String [] serverlist = configurationmanager. receivettings ["memcached. serverlist"]. Split (separator );

// Initialize the pool for memcache servers
Try
{
Sockiopool pool = sockiopool. getinstance ();
Pool. setservers (serverlist );

Pool. initconnections = 3;
Pool. minconnections = 3;
Pool. maxconnections = 50;

Pool. socketconnecttimeout = 1000;
Pool. Fig = 3000;

Pool. maintenancesleep = 30;
Pool. Failover = true;

Pool. Nagle = false;
Pool. initialize ();
}
Catch (exception ERR)
{
// Here we can use log4net to record the error!
}

Note that the appsettings ["memcached. serverlist"] is set in Web. config. Therefore, the following line must be set in the child node of the appsettings in Web. config.
<Add key = "memcached. serverlist" value = "Maid: 11211"/>
Start the debugging server. If no error log is recorded, the I/O connection pool is successfully opened.
6. Use memcached
Finally, we entered the topic, but before using it, we still need to prepare some data.
Create an object class people and add the serializable attribute !!!
Add a table to the corresponding database. The field corresponds to the entity class and some test data is inserted. The design of the persistence layer and business layer is skipped. They are responsible for providing some data with customizable return types, such as ilist and dataset.
Memcached is easy to use. For example, a group of people-type data is retrieved in the background and stored in an arraylist called peoplelist. This arraylist must be used frequently.
Memcachedclient MC = new memcachedclient ();
MC. enablecompression = true;
MC. Set (Key, peoplelist );
The above key is used to access this arraylist key, and the data in memcached is saved as a key-value pair.
Once MC. keyexists (key) is true, return MC. Get (key) as arraylist is used to extract data. When deleting the data, return MC. Delete (key); is used. You can think about it yourself.

The above is just a demonstration. In fact, data cache is a complex and tedious task. It requires not only hierarchical optimization of the background code, but also database policies and tuning for access to large data volumes.

 

Http://www.chinahtml.com/0707/asp-118489071915107.html

Implementation of memcached: http://tech.it168.com/a2009/0907/675/000000675239.shtml in. net

Improve the Performance of. Net Applications with memcached (Zhou Gong): http://zhoufoxcn.blog.51cto.com/792419/528212

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.