Asp. NET in use Memcached__.net

Source: Internet
Author: User
Tags memcached prepare log4net
Now some. NET developers began to discard the asp.net built-in caching mechanism, instead using memcached--, a distributed memory caching system, originally developed by Danga Interactive for the LiveJournal site.

A fundamental problem with caching is how to handle obsolete data. When running on a separate Web server, you can easily clear a cache that has been confirmed to have been changed. Unfortunately, ASP. NET does not have a good way to support multiple servers. The cache on each server is ignorant of other cache changes.

Asp. NET allows a cache to be invalidated by triggers based on file system and database tables. However, there are also problems, such as the need for database triggers to use expensive polling and the lengthy programming of the trigger itself. However, we still have other options.

Unlike the ASP.net built-in caching mechanism, memcached is a distributed caching system. Any Web server can update or delete a cache entry, and all other servers will automatically get updated content the next time they access these cached items. This is accomplished by storing these cached items on one or more cache servers. Each cache entry is assigned to a server based on the hash value of its keyword. Content from China Webmaster Information Network (www.chinahtml.com)

On the face of it, Memcached's API for asp.net is like the built-in API. This makes it easy for developers to switch to memcached, simply by finding and replacing them in code.

However, just making it work is not enough, and there are some issues to be aware of if you want to use it correctly in a large web Farms: a large site. Richard Jones wrote: Content from the Chinese Webmaster Information Network (www.chinahtml.com)

When we add many nodes, the usefulness of the Get_multi function is reduced-this may be due to a separate page that requires access to almost all memcached instances. I read about Facebook somewhere that the very hot campus social network is segmenting their memcached clusters to improve Get_multi performance (for example, all user data is placed on a subset node called MC). Can someone tell me the effect of doing this?

A recommended solution is to not generate hashing values based on the keyword of the cached item. This will allow developers to have all the cached items needed on a given page to be kept on the same server as possible. Unfortunately, based on the location of the data saved rather than based on the cache item itself keyword to generate hashing, it is easy to produce errors, need to be carefully implemented (this algorithm).

ASP. NET in memcached

One, prepare
You need to have the software:
Vs.net (05/08)
Sql server
memcached Server side and Client class library (open source software, download)
Among them, the client class library includes the following several DLLs:
Memcached.ClientLibrary.dll
ICSharpCode.SharpZipLib.dll
Log4net.dll
Second, install memcached server side
Copy Memcached.exe to any directory, such as C:, and enter at the command line:
memcached.exe-d Install
Memcached will serve as a service resident system memory
Third, establish the ASP.net project
Create a Asp.netweb project, named Mmcweb, to add references to several of the client class libraries mentioned above.
Four, configure
Memcached used log4net, so we first configure Log4net
Locate the configsections node in Web.config and add the following
<section name= "log4net" type= "log4net". Config.log4netconfigurationsectionhandler, log4net "/>

In addition to the configsections node, add the following:
<log4net>
<appender name= "Rollinglogfileappender" type= "log4net". Appender.rollingfileappender ">
<param name= "File" value= "logfiles/"/>
<param name= "Appendtofile" value= "true"/>
<param name= "maxsizerollbackups" value= "ten"/>
<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]%-5level%logger-%NDC%message%newline"/ >
</layout>
</appender>
<appender name= "Consoleappender" type= "log4net". Appender.consoleappender ">
<layout type= "log4net. Layout.patternlayout ">
<param name= "Conversionpattern" value= "%d{yyyy-mm-dd HH:mm:ss} [%thread]%-5level%logger-%NDC%message%newline"/& Gt
</layout>
</appender>
<root>
<level value= "All"/>
<appender-ref ref= "Rollinglogfileappender"/>
<appender-ref ref= "Consoleappender"/>
</root>
<logger name= "Memcached.clientlibrary" >
<level value= "WARN"/>

</logger>
</log4net>
Start debugging, if there is no configuration error prompts, and in the Web Site Directory folder LogFiles, it shows that log4net configuration succeeded.

Five, initialize Sockiopool
What Sockiopool is. Sockiopool is the memcached client provides a socket connection pool, in layman's terms, is the object that exchanges data with the memcached server side. The Sockiopool is initialized once the application is started, and I put this work in GLOBAL. ASAX. CS in the Application_Start method
Char[] Separator = {', '};
string[] serverlist = configurationmanager.appsettings["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. Sockettimeout = 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, so the following line is required for the Web.config appsettings child node
<add key= "memcached.serverlist" value= "127.0.0.1:11211"/>
Start the debug server, and if there is no error logging, the IO connection pool has been successfully opened.
Vi. Use of memcached
It's finally getting to the point, but before we use it, we need to prepare some data.
Create an entity class people and add the Serializable property ...
In the corresponding database, add a table, field corresponding to the entity class, insert some test data. The design of the persistence layer and the business layer is skipped, they are responsible for providing some data, the return type can be customized, if Ilist,dataset.
Memcached is very simple to use, such as the background to retrieve a group of people type of data, placed in a ArrayList called Peoplelist, and this ArrayList to use frequently, only need this
memcachedclient mc = new Memcachedclient ();
Mc. EnableCompression = true;
Mc. Set (key, peoplelist);
The key above is used to access the ArrayList keys, and the data in the memcached are stored as key-value pairs.
Once the MC. Keyexists (Key) is true, use return MC. Get (key) as ArrayList extract the data, delete when using return MC. Delete (key), and so on. I can figure it out for myself.

The above is only demo, in fact, data caching is a complex and cumbersome work, not only requires the hierarchical optimization of code, but also requires the database on the large amount of data access strategy and tuning.

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

. Implementation of distributed caching system under net memcached:http://tech.it168.com/a2009/0907/675/000000675239.shtml

Use memcached to improve the performance of. NET Applications (week): 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.