Install memcached and use Memcached. ClientLibrary in. NET.
Preface
Let me take your 20 minutes to make sure that you use memcached to cache data in. net. This increases data reading efficiency and reduces database pressure.
This article focuses on: memcached distributed cache Load Balancing configuration ratio, data compression, detailed socket configuration, and common methods in. net.
What is memcached, What Is memcached, and why it is used? This article does not introduce it. I suggest Baidu encyclopedia. Let's take a look at it. It's even better than me, haha, loading.
Download and install memcached in windows
: Http://pan.baidu.com/s/1yVILw extraction password: 5gx9
Http://memcached.org/
After the download is complete
1. Open the SetupFile installation folder.
2. Open the cmd command interface. Do not forget to start the service in the windows service.
3. The above installation and start operations are performed in the default environment. You can set the following parameters during installation:
-P listening port
-L connected IP address. The default value is local
-D start: start the memcached service.
-D restart: restart the memcached service.
-D stop | shutdown the running memcached Service
-D install the memcached Service
-D uninstall memcached Service
-U runs as the identity (only valid when running as root)
-MB maximum memory usage, in MB. The default value is 64 MB.
-An error is returned when M memory is used up, instead of deleting items.
-C: Maximum number of simultaneous connections. The default value is 1024.
-F block size growth factor, default value: 1.25
-N: minimum allocation space. The default value of key + value + flags is 48.
-H Show Help
4. You can install it. The following describes how to operate memcached in c.
Use memcached first
1. Download the three dll files of the client, ICSharpCode. SharpZipLib. dll, log4net. dll, and 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"}; // initialize the SockIOPool pool = SockIOPool. getInstance (); // set the server list pool. setServers (servers); // set the Server Load balancer ratio pool between servers. setWeights (new int [] {1}); // create a connection pool during initialization. initConnections = 3; // pool of least connections. minConnections = 3; // maximum number of connections pool. maxConnections = 5; // maximum idle time of the connection. The value below is set to 6 hours (unit: ms), which exceeds the set time. The connection will be released from the pool. maxIdle = 1000*60*60*6; // The timeout time of the socket connection. The following settings indicate no timeout (in ms), that is, the connection pool is maintained. socketConnectTimeout = 0; // The Supermarket time for communication. Set it to 3 seconds (unit: ms ),. net version does not implement pool. socketTimeout = 1000*3; // specifies the activation time between maintenance threads. The value below is set to 30 seconds (in seconds). If it is set to 0, the maintenance thread pool is not enabled. maintenanceSleep = 30; // set the fault mark pool of the SocktIO pool. failover = true; // whether to use the nalgle Algorithm for TCP/IP communication ,. net version does not implement pool. nagle = false; // maximum time (unit: ms) of a single socket task. After this time, the socket is forcibly middle-end and the current task fails. Pool. maxBusy = 1000*10; pool. initialize (); cache = new MemcachedClient (); // whether to enable data compression: If compression is enabled, data that exceeds the threshold will be stored in the compressed form cache. enableCompression = false; // compression setting. If the size exceeds the specified value, the data is compressed. // cache. compressionThreshold = 1024*1024;} class Program {static void Main (string [] args) {// a cache AMemcached with the key as a and value as 123. cache. add ("a", "123"); // read the cache value var s = AMemcached whose key is. cache. get ("a"); // output Console. writeLine (s); Console. readKey ();}}
Note: first, let us know a good message. memcached is so simple that you can use it. If you are interested, you can use it in AMemcached. add a bit later in the cache to check whether there are other good methods for adding, deleting, modifying, querying, and reloading in this class library. If you want to learn more, continue.
Detail. NET Memcached. ClientLibrary
1. About the configuration and application of memcached distributed cache
String [] servers = {"172.18.5.66: 11211", "192.168.10.121: 11211"}; // initialize the SockIOPool pool = SockIOPool. getInstance (); // set the server list pool. setServers (servers); // set the Server Load balancer ratio pool between servers. setWeights (new int [] {1, 10 });
Note:
1. Install the memcached server on 172.18.5.66 and 192.168.10.121.
2. pool. SetWeights 1 and 10 here mean the proportion of Server Load balancer. For example, if there are 11000 pieces of data, the approximate data distribution is about 1000 pieces of data in 172.18.5.66. The other is about 10000.
3. The memcached server is not capable of load balancing, but implemented by the memcachedClient. The core of the specific data access implementation is to use a consistent Hash algorithm to distribute the key-value to a server.
2. About memcached's data compression Mechanism
// Whether to enable data compression: If compression is enabled, data that exceeds the threshold will be stored in the compressed cache. enableCompression = false; // compression setting. If the size exceeds the specified value, the data is compressed. // cache. compressionThreshold = 1024*1024;
Note:
1. This processing is performed in the MemcachedClient object. It sets the EnableCompression attribute and indicates whether to use compression. If compression is enabled, ICSharpCode is used. the SharpZipLib class library compresses data that exceeds the preset size.
2. The CompressionThreshold attribute is the compressed threshold value. The default value is 15 kb. If the threshold value is exceeded, the memcached communication protocol is used, when storing data, each data item is assigned a 16-fold flag indicating whether the record is compressed. If there is compression, the extracted data is extracted. If the threshold value is not exceeded, the data is not compressed and stored directly.
3. How to use multiple SocketIO pools on the client
Class AMemcached {public MemcachedClient cache; public AMemcached (string poolName) {string [] servers = {"172.18.5.66: 11211", "192.168.10.121: 11211 "}; // initialize the SockIOPool pool = SockIOPool. getInstance (poolName); // sets the server list pool. setServers (servers); // set the Server Load balancer ratio pool between servers. setWeights (new int [] {1, 10}); // create a connection pool during initialization. initConnections = 3; // pool of least connections. minConnections = 3; // maximum number of connections pool. maxConnectio Ns = 5; // The maximum idle time of the connection. The value below is set to 6 hours (unit: ms). When the set time is exceeded, the connection will be released from the pool. maxIdle = 1000*60*60*6; // The timeout time of the socket connection. The following settings indicate no timeout (in ms), that is, the connection pool is maintained. socketConnectTimeout = 0; // The communication timeout time. Set it to 3 seconds (unit: ms ),. net version does not implement pool. socketTimeout = 1000*3; // specifies the activation time between maintenance threads. The value below is set to 30 seconds (in seconds). If it is set to 0, the maintenance thread pool is not enabled. maintenanceSleep = 30; // set the fault mark pool of the SocktIO pool. failover = true; // whether to use the nalgle Algorithm for TCP/IP communication ,. net version does not implement pool. nagle = false; // socke T the maximum time (unit: ms) of a single task. After this time, the socket will be forcibly middle-end, and the current task will fail. Pool. maxBusy = 1000*10; // initialize some values and establish a connection pool with the MemcachedServer segment. initialize (); cache = new MemcachedClient (); // whether to enable data compression: If compression is enabled, data that exceeds the threshold will be stored in the compressed form cache. enableCompression = false; // compression setting. If the size exceeds the specified value, the data is compressed. // cache. compressionThreshold = 1024*1024; // specify the SockIO pool cache accessed by the client. poolName = poolName ;}} class Program {static void Main (string [] args) {// a new AMemcached ("me") cache with the key of a and value of 123 "). cache. add ("B", 123); // read the cache value var s = new AMemcached ("me") whose key is "). cache. get ("B"); // output Console. writeLine (s); Console. readKey ();}}View Code
Note: In the scenario of SocketIoPool, if your system uses memcached cache data from machines A and B, and A and B are irrelevant and there is no data exchange and sharing, in this case, you can set the poolName to read and write the machine. You do not need to configure multiple client parameters.
4. Let's talk about the troubleshooting of memcached.
// Set the fault mark pool. Failover = true for the SocktIO pool;
Note: memcached's applause transfer is a processing mechanism when a normal node fails to become a dead node.
1. Enable failover: If a socket exception occurs, the node is added to _ hostDead, which stores the dead node attribute. New requests are mapped to the dead server, check the time interval attribute _ hostDeadDuration (set to 100 ms by default) of the attempt to connect to the dead node. If the specified time interval is not reached, the key will be mapped to the available server for processing, if the time interval is reached, reconnect the node. If the connection succeeds, the node is removed from _ hostDead. If the connection fails, the interval is doubled and the next reconnection time is extended.
2. Do not enable failover: new requests will be mapped to the dead server and try to re-establish the socket link. If the connection fails, null is returned or the operation fails.
5. Let's talk about the key and value in key-value.
1. The key length on the server is limited to 250 characters. We recommend that you use a shorter key, but do not repeat it.
2. The value size is limited to 1 mb. If it is large, it can be compressed. If it is large, it may be split into multiple keys.