. memcached Caching and Memcached.clientlibrary tutorial for use in net

Source: Internet
Author: User
Tags foreach datetime failover memcached memcached stats socket time interval log4net

memcached downloads and installs under Windows

Official website: http://memcached.org/

When the download is complete

1, open the SetupFile installation folder.


2, open the CMD command interface.

Don't forget to start the service in the Windows service.

3, the above installation and start-up are in the default environment, in the installation of the following parameters can be set:

-P Listening Port
The IP address of the-l connection, the default is native
-D Start memcached service
-D Restart Restart memcached service
-D Stop|shutdown shut down the running memcached service
-D Install installation memcached service
-d Uninstall Uninstall memcached service
-U Run as (only valid when run as root)
-m maximum memory usage, in MB. Default 64MB
-Returns an error when M memory is exhausted instead of deleting the item
-C Maximum Simultaneous connection number, default is 1024
-F Block size growth factor, default is 1.25
-N Minimum allocation space, key+value+flags default is 48
-H Display Help

4, so you can install it well. Let's see how we can operate memcached in the C # language.


memcached Use

1, download the client's 3 Dll,icsharpcode.sharpziplib.dll,log4net.dll,memcached.clientlibrary.dll

2. Follow me to create a simple console application


Class amemcached
{
public static memcachedclient cache;
Static amemcached ()
{
String[] Servers = {"172.18.5.66:11211"};
Initializing pool
Sockiopool pool = sockiopool.getinstance ();
Set up a list of servers
Pool. Setservers (servers);
Set ratio of load balancing between servers
Pool. Setweights (New int[] {1});
Create the number of connections when initializing
Pool. Initconnections = 3;
Minimum number of connections
Pool. Minconnections = 3;
Maximum number of connections
Pool. MaxConnections = 5;
The maximum idle time for the connection, set to 6 hours (unit ms), over which time the connection will be released
Pool. Maxidle = 1000 * 60 * 60 * 6;
The timeout for the socket connection, and the following setting indicates no timeout (unit ms), which keeps the link state
Pool. socketconnecttimeout = 0;
Communication of the supermarket time, set below to 3 seconds (unit ms),. NET version is not implemented
Pool. sockettimeout = 1000 * 3;
Maintain thread interval activation time, set to 30 seconds (unit s), set to 0 to indicate that maintenance threads are not enabled
Pool. Maintenancesleep = 30;
Set the fault flag for the Socktio pool
Pool. Failover = true;
Whether to use the Nalgle algorithm for TCP/IP traffic, the. NET version is not implemented
Pool. Nagle = false;
The maximum time of the socket single task (unit ms), more than this time socket will be forced to end, the current task failed.
Pool. maxbusy = 1000 * 10;
Pool. Initialize ();
cache = new Memcachedclient ();
Whether to enable compressed data: If compression is enabled, data compression longer than the threshold data will be stored in a compressed form
Cache. EnableCompression = false;
Compression settings, compressed with more than the specified size
Cache.compressionthreshold = 1024 * 1024;
}
}
Class Program
{
static void Main (string[] args)
{
A cache with key A,value 123
AMEMCACHED.CACHE.ADD ("A", "123");
read out the cache value for key A
var s = AMemcached.cache.Get ("a");
Output
Console.WriteLine (s);
Console.readkey ();
}
}


Note: First of all tell you a good news, memcached is so simple, you have been able to use, if interested, then in the back of the Amemcached.cache dot, look at this class library there are those about add and delete to check the overload of a good way. If you want to know more about it, keep looking down.


fine goods. NET Memcached.clientlibrary

1, talk about the memcached and application of distributed caching


String[] Servers = {"172.18.5.66:11211", "192.168.10.121:11211"};
Initializing pool
Sockiopool pool = sockiopool.getinstance ();
Set up a list of servers
Pool. Setservers (servers);
Set ratio of load balancing between servers
Pool. Setweights (New int[] {1, 10});



Note:

1, in 172.18.5.66, and 192.168.10.121 two machines with memcached server.

2, pool. Setweights here 1 and 10 mean that load balancing ratio, if 11,000 data, the approximate data distribution is: 172.18.5.66 distribution 1000 data around. The other one is about 10,000.

3, memcached server does not have the ability to load balance, but memcachedclient implementation, the core of the implementation of specific access data is the use of a consistent hash algorithm, the Key-value distributed to a single servers inside.

2, talk about the memcached data compression mechanism

Whether to enable compressed data: If compression is enabled, data compression longer than the threshold data will be stored in a compressed form
Cache. EnableCompression = false;
Compression settings, compressed with more than the specified size
Cache.compressionthreshold = 1024 * 1024;

Note:

1, this processing is in the Memcachedclient object, set this EnableCompression property, whether use compression meaning, if enabled compression function, The Icsharpcode.sharpziplib class library makes data compression when the data exceeds the preset size.

2, Compressionthreshold This property is the compression of the threshold, the default is 15K, if more than the set threshold is used memcached communication protocol, storage data for each data item allocated a 16 for the flag said, as a record whether there is compression, If there is compression, extract the data is to extract. If no more than the threshold is not compressed, direct storage.

3, talk about how to use the client multiple Socketio pool


Class amemcached
{
public memcachedclient Cache;
Public amemcached (String poolname)
{
String[] Servers = {"172.18.5.66:11211", "192.168.10.121:11211"};
Initializing pool
Sockiopool pool = sockiopool.getinstance (poolname);
Set up a list of servers
Pool. Setservers (servers);
Set ratio of load balancing between servers
Pool. Setweights (New int[] {1, 10});
Create the number of connections when initializing
Pool. Initconnections = 3;
Minimum number of connections
Pool. Minconnections = 3;
Maximum number of connections
Pool. MaxConnections = 5;
The maximum idle time for the connection, set to 6 hours (unit ms), over which time the connection will be released
Pool. Maxidle = 1000 * 60 * 60 * 6;
The timeout for the socket connection, and the following setting indicates no timeout (unit ms), which keeps the link state
Pool. socketconnecttimeout = 0;
The timeout for the communication, which is set to 3 seconds (unit ms). NET version is not implemented
Pool. sockettimeout = 1000 * 3;
Maintain thread interval activation time, set to 30 seconds (unit s), set to 0 to indicate that maintenance threads are not enabled
Pool. Maintenancesleep = 30;
Set the fault flag for the Socktio pool
Pool. Failover = true;
Whether to use the Nalgle algorithm for TCP/IP traffic, the. NET version is not implemented
Pool. Nagle = false;
The maximum time of the socket single task (unit ms), more than this time socket will be forced to end, the current task failed.
Pool. maxbusy = 1000 * 10;
Initialize some values and establish a connection with the Memcachedserver segment
Pool. Initialize ();
cache = new Memcachedclient ();
Whether to enable compressed data: If compression is enabled, data compression longer than the threshold data will be stored in a compressed form
Cache. EnableCompression = false;
Compression settings, compressed with more than the specified size
Cache.compressionthreshold = 1024 * 1024;
Specify Sockio pool for client access
Cache. poolname = poolname;
}


}
Class Program
{
static void Main (string[] args)
{
A cache with key A,value 123
New Amemcached ("Me"). Cache. ADD ("B", 123);
read out the cache value for key A
var s = new amemcached ("Me"). Cache. Get ("B");
Output
Console.WriteLine (s);
Console.readkey ();
}
}


Note: Use the Socketiopool scenario, if your system uses A,B two machine memcached cache data, and a,b is irrelevant, no data sharing, then you can according to set poolname to handle reading and writing that machine. Instead of multiple, configure the client's various parameters repeatedly.

4, talk about the memcached of the fault transfer processing

Set the fault flag for the Socktio pool
Pool. Failover = true;

Note:memcached's applause transfer is a set of processing mechanism when the normal node fails into a dead node.

1. Turn on failover: If a socket exception occurs, the node is added to the _hostdead that holds the dead node properties, and the new request is mapped to dead server, which detects the time interval attribute that attempts to connect to the dead node _ Hostdeadduration (default is 100ms), key is mapped to available server processing if a set interval is not reached, and if time interval is reached, attempt to relink and the connection succeeds in removing the node from the _hostdead. If the connection fails, the interval time is doubled and the next reconnection time is stretched.

2. Do not turn on failover: New requests are mapped to the dead server, try to re-establish the socket link, if the connection fails, return null or the operation fails.

5, talking about the key and value in Key-value

1, key at the service end of the length limit of 250 characters, it is recommended to use a shorter key but do not repeat.

2, the value of the size limit of 1MB, if large pull, you can use compression, if it is large, it may be split into multiple key.



Memcached. NET (C #) instance analysis

One: Installation of memcached

Step1. Download Memcache's Windows stable version (where I downloaded the version of memcached 1.2.1 for Win32 binaries (Dec 23, 2006), unzip it under a disk, such as in c:\memcached
Step2. Enter ' c:\memcached\memcached.exe-d install ' installation at terminal (also known as cmd Command interface)
Step3. Re-enter: ' c:\memcached\memcached.exe-d start ' starts.

PS: Later memcached will automatically start as a service for Windows each time it is powered on. This way the server side is already installed.


Two:. NET memcached Client Library


Download file: https://sourceforge.net/projects/memcacheddotnet/
Put the Commons.dll,icsharpcode.sharpziplib.dll,log4net.dll,memcached.clientlibrary.dll, etc. into the bin directory
Referencing Memcached.ClientLibrary.dll

Program Instance

Code

Code highlighting produced by Actipro Codehighlighter (freeware) http://www.CodeHighlighter.com/-->using System;
Using System.Collections;
Using Memcached.clientlibrary;
Using System.Text;

Namespace Memcache
{
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
if (request["action"] = = "clear")
This.clear ();
Else
This.test ();
}
}

public void Clear ()
{
String[] Servers = {"192.168.1.113:11211", "192.168.202.128:11211"};

Initializing pool
Sockiopool pool = sockiopool.getinstance ();
Pool. Setservers (servers);
Pool. Initconnections = 3;
Pool. Minconnections = 3;
Pool. MaxConnections = 5;
Pool. socketconnecttimeout = 1000;
Pool. Sockettimeout = 3000;
Pool. Maintenancesleep = 30;
Pool. Failover = true;
Pool. Nagle = false;
Pool. Initialize ();
memcachedclient mc = new Memcached.ClientLibrary.MemcachedClient ();
Mc. EnableCompression = false;
Mc. Delete ("cache");
Mc. Delete ("Endcache");
Response.Write ("Empty cache succeeded");
}


public void Test ()
{
Distributed MEMCACHEDF Service IP ports
String[] Servers = {"192.168.1.113:11211", "192.168.202.128:11211"};

Initializing pool
Sockiopool pool = sockiopool.getinstance ();
Pool. Setservers (servers);
Pool. Initconnections = 3;
Pool. Minconnections = 3;
Pool. MaxConnections = 5;
Pool. socketconnecttimeout = 1000;
Pool. Sockettimeout = 3000;
Pool. Maintenancesleep = 30;
Pool. Failover = true;
Pool. Nagle = false;
Pool. Initialize ();
Client instance
memcachedclient mc = new Memcached.ClientLibrary.MemcachedClient ();
Mc. EnableCompression = false;
StringBuilder sb = new StringBuilder ();
Write Cache
Sb. Appendline ("Write Cache test:");
Sb. Appendline ("<br>_______________________________________<br>");
if (MC. Keyexists ("cache"))
{
Sb. Appendline ("Cached cache already exists");
}
Else
{
Mc. Set ("Cache", "Write Cache Time:" +datetime.now.tostring ());
Sb. Appendline ("Cache has been successfully written to cache");
}
Sb. Appendline ("<br>_______________________________________<br>");
Sb. Appendline ("read cache content as follows:<br>");
Sb. Appendline (MC. Get ("cache"). ToString ());

Test cache Expiration
Sb. Appendline ("<br>_______________________________________<br>");
if (MC. Keyexists ("Endcache"))
{
Sb. Appendline ("Cache Endcache already exists, expires as:" + MC. Get ("Endcache"). ToString ());
}
Else
{
Mc. Set ("Endcache", DateTime.Now.AddMinutes (1). ToString (), DateTime.Now.AddMinutes (1));
Sb. Appendline (Cache has been updated write to Endcache, write time: "+ DateTime.Now.ToString () +" Expires: "+ DateTime.Now.AddMinutes (1). ToString ());
}

Profiling Cache State
Hashtable HT = MC. Stats ();
Sb. Appendline ("<br>_______________________________________<br>");
Sb. Appendline ("Memcached Stats:");
Sb. Appendline ("<br>_______________________________________<br>");
foreach (DictionaryEntry de in HT)
{
Hashtable info = (Hashtable) de. Value;
foreach (DictionaryEntry de2 in info)
{
Sb. Appendline (De2. Key.tostring () + ":&nbsp;&nbsp;&nbsp;&nbsp;" + de2. Value.tostring () + "<br>");
}
}
Response.Write (sb.) ToString ());
}
}
}

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.