C # memcache,

Source: Internet
Author: User
Tags log4net

C # memcache,
Overview

Memcache is an open-source distributed high-speed cache system. It is composed of a server and a client. It runs on one or more servers in the form of a daemon (listener) and receives client connections and operations at any time. Memcache caches data objects to the memory and maintains a unified and huge hash table in the memory. Simply put, the data is called to the memory and then read from the memory, which greatly improves the reading speed. Memcache stores objects to the memory based on the hashmap of a storage key/value pair. Memcache is written in C, but the client can be written in any language and communicate with the daemon through the memcached protocol.

  Features:  

  • There is no limit on the data size of items that can be stored in Memcached, as long as the memory is sufficient.
  • Memcached has a maximum memory usage of 2 GB for a single process in a 32-bit system. If it is in a 64-bit system, there is no limit. This is because a 32-bit system limits that a single process can use a maximum of 2 GB of memory, to use more memory, you can enable multiple Memcached processes on multiple ports.
  • The maximum data expiration time of 30 days. If it is set to permanent, it will also expire at this time. The constant REALTIME_MAXDELTA
  • The maximum data size of a single item is 1 MB. If the data size exceeds 1 MB, It is not stored. The constant POWER_BLOCK 1048576 is used for control.
Install Memcache in Windows

After learning about some basic information about memcache, try to install the memcache server on windows.

Steps:

1. Window + R: Enter cmd
2. Perform the G drive: Input G:
3. Run the installation directory of Memcached for window 32/64: Enter cd CK \ memcached_en32or64 \ x64
4. install memcached: Enter memcached-d install
5. start the service: Enter memcached-d start

After starting the service, you can see memcached.exe in the Windows process.

Memcached-d start | stop | shutdown | restart | uninstall | install start | stop | restart | uninstall | install.

The installation steps are not complex. First, find the file (memcached.exe) path. Second: memcached-d install on OK ..

Basic default parameters:

-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

After the server operation is complete, telnet to the service test on the local machine. (If you are prompted that the telnet command does not exist, you need to go to the control panel to enable the windows tel service function. To enable the tel function for win7, follow these steps: [Control Panel]-> [program and function]-> [enable or disable the window function], and then find and check tel. The steps for other Windows systems are similar .)

Test whether telnet is running properly. telnet 172.21.0.192 11211

Press ctrl +] to start the display. Otherwise, the input information cannot be displayed. After the callback function is started successfully, see:

Then press enter to enter the parameter stats:

Installation and testing have been completed ..

Instance code

There are many C # version Memcached client programs. Here we use the Memcached. ClientLibrary. dll client call method, which requires two DLL calls:

Memcached. ClientLibrary. dll (Memcached client Class Library)

Log4net. dll (log4net provides log records for Memcached) DLL: [Click to download]

Reference the two dll files in the project. After referencing log4net. dll, you still need to perform a series of configuration work. The configuration of log4net is introduced in the previous blog.

[Log4Net log configuration [with source code]

Note: Memcached. ClientLibrary. dll has a version relationship with log4net. dll.

2. If you use WinForm or the console application to display the log4net configuration file independently, you need to set it up in App. config.

The Log4Net. config attribute "Copy to output directory": "Always copy ". Otherwise, an error is reported if the corresponding configuration information cannot be found in the bin directory.

Memcache stores objects to the memory based on the hashmap of a storage key/value pair. Therefore, we can understand that key-value pairs are mainly used to operate hashmap.

The following are some simple operations [add, delete, modify, query, and set the expiration time]:

// Set string SockIOPoolName = "Test_SockIOPoolName"; string [] MemcacheServiceList = {"172.21.0.192: 11211"}; // set SockIOPool SPool = SockIOPool. getInstance (SockIOPoolName); SPool. setServers (MemcacheServiceList); SPool. initialize (); // instantiate ClientMemcachedClient MClient = new MemcachedClient (); MClient. poolName = SockIOPoolName; Console. writeLine ("1. create memcache cache Hello World "); MClient. add ("Key1001", "Hello World"); Console. writeLine ("2. query Cache Information {0} ", MClient. get ("Key1001"); Console. writeLine ("3. modify memcache cache Hello World "); MClient. set ("Key1001", "Hello World-modified version"); Console. writeLine ("4. query Cache Information {0} ", MClient. get ("Key1001"); if (MClient. keyExists ("Key1001") {Console. writeLine ("5. delete memcache cache "); MClient. delete ("Key1001");} if (MClient. keyExists ("Key1001") Console. writeLine (MClient. get ("Key1001"); else Console. writeLine ("6. delete deleted "); MClient. add ("Key1002", "I have set the expiration time to 1 minute", DateTime. now. addMinutes (1); while (true) {if (MClient. keyExists ("Key1002") {Console. writeLine ("key: Key1002 Value: {0}, current time: {1}", MClient. get ("Key1002"), DateTime. now); Thread. sleep (20000);} else {Console. writeLine ("key: Key1002 I have expired, current time: {0}", DateTime. now); break ;}}

 

Output result:

Memcached distributed storage

Assume that the memcached server has node1 ~ Three node3 applications need to save data with the keys "tokyo", "kanagawa", "CHBA", "saitama", and "gunma.

 

First, add "tokyo" to memcached ". After "tokyo" is passed to the client library, the algorithm implemented by the client determines the memcached server that stores data based on the "key. After the server is selected, run the command to save "tokyo" and its value.

Similarly, "kanagawa", "CHBA", "saitama", and "gunma" are both selected first and then saved. Next, obtain the saved data. The key "tokyo" to be obtained is also passed to the function library. The function library uses the same algorithm as the data storage algorithm to select a server based on the "key. If the algorithm used is the same, you can select the same server as the storage server and then send the get command. As long as the data is not deleted for some reason, you can get the saved value.

In this way, memcached is distributed by storing different keys on different servers. When the number of memcached servers increases, keys will be dispersed. Even if a memcached server fails to connect, other caches will not be affected, and the system will continue to run. (Reference: memcached comprehensive analysis)

// Parameter string [] MemcacheServiceList = {"172.21.0.192: 11211", "172.21.0.28: 11211", "172.21.13.246: 11211"}; // set SockIOPool SPool = SockIOPool. getInstance (); SPool. setServers (MemcacheServiceList); SPool. initialize (); MemcachedClient MClient = new MemcachedClient (); MClient. flushAll (); int count = 5; var time = Stopwatch. startNew (); for (int I = 0; I <count; I ++) {MClient. add (I. toString (), "value" + I);} Con Sole. WriteLine ("memcached cache created successfully. Time consumed: {0} ", time. elapsedTicks); time = Stopwatch. startNew (); for (int I = 0; I <count; I ++) {if (MClient. keyExists (I. toString () {Console. writeLine ("key: {0 }. value: {1} ", I, MClient. get (I. toString ();} else {Console. writeLine ("-------- failed to query data key: {0} --------", I) ;}} Console. writeLine ("memcached cache data query is complete. Time consumed: {0} ", time. ElapsedTicks); SPool. Shutdown ();View Code

[Instance Code]

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.