Memcached Summary: memcached

Source: Internet
Author: User
Tags couchbase telnet program

Memcached Summary: memcached

Memcached instructions

What is Memcached?

Memcached is a high-performance distributed memory object Cache System for dynamic Web applications to reduce database load. It caches data and objects in the memory to reduce the number of times the database is read, so as to provide dynamic, database-driven website speed. Memcached is based on a hashmap that stores key/value pairs. Its daemon is written in C, but the client can write it in any language and communicate with the daemon through memcached protocol. However, it does not provide redundancy (for example, copying its hashmap entries). When a server S stops running or crashes, all key/value pairs stored on S will be lost.

Basic Principles of Memcached
  • Socket server
  • Data: Key-Value Pair Storage
  • Memory Processing Algorithm:
    • In essence, it is a large hash table. The key cannot exceed 255 characters.
    • Memory Model: Memcache pre-partitions disposable memory space (Slab). Each partition is further divided into multiple chunks (1 MB), but in the same partition: the block length (bytes) is fixed.
    • Insert data: Find the appropriate length of the block, and then insert, there will be a waste of memory.
    • LRU, idle> expired> Minimum Access
    • Inert deletion: it does not provide a mechanism for monitoring data to expire, but is inert. When a key data is queried, It is discarded if it expires.
  • Cluster construction principle:
    • The Memcache server does not provide the cluster function, but the cluster configuration is implemented through the client driver.
    • OHow the client implements the cluster: first, the client configures the ip address and port list of Multiple Cluster machines. Then, before writing the data, the client driver first performs hash processing on the key to obtain the hash value, then performs remainder on the total number of machines, and then selects the machine corresponding to the remainder.
2. Download and install Windows 2.1

Memcached 1.4.4 for Windows 32-bit

2.2 install Memcache as a system service

Download dll address: http://www.dll-files.com/dllindex/dll-files.shtml? Msvcr71

NOTE:
Or you can start it directly without installation.
In the future, memcached will be used as a windows service to automatically start every time it is started. In this way, the server has been installed.

If the download is a binary version, you can directly run it. You can add parameters to set it.

2.3 Common commands

-P <num> listening port

-L <ip_addr> 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 <username> runs as <username> (valid only when running as root)

-M <num> 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 <num> maximum number of simultaneous connections. The default value is 1024.

-F <factor> block size growth factor. The default value is 1.25.

-N <bytes> minimum allocated space. The default value of key + value + flags is 48.

-H Show Help

Then you can use the. net memcached client to try it out.

3. Client use 3.1. telnet Introduction The Telnet protocol is a member of the TCP/IP protocol family and is the standard protocol and main method of the Internet remote login service. It provides users with the ability to complete remote host work on local computers. Use the telnet program on the terminal user's computer to connect to the server. End users can enter commands in the telnet program. These commands will run on the server, just as they are directly entered on the server console. You can control the server locally. To start a telnet session, you must enter the user name and password to log on to the server. Telnet is a common method to remotely control Web servers. 3.2 use telnet to connect to memcached using telnet.
1.Use a windows system name prompt.
Input: telnet localhost 11211 to connect. (If the connection fails, it should be because the telnet client is not enabled, and win7 is disabled by default ).
2.Use the connection software PuTTy.
PuTTY is a Telnet, SSH, rlogin, pure TCP, and serial interface connection software. Earlier versions only support Windows platforms. In recent versions, they began to support various types of Unix platforms and are intended to be transplanted to Mac OS X.

: PuTTy

3.3 basic memcached client commands
If everything is normal, you should receive a telnet response, which indicatesConnected to localhost(Already connectedLocalhost). If this response is not received, the previous steps should be returned and the source files of libevent and memcached have been successfully generated.
You have now logged on to the memcached server. Later, you will be able to communicate with memcached through a series of simple commands. Nine memcached client commands can be divided into three types:
  • Basic
  • Advanced
  • Management
You will use five basic memcached commands to perform the simplest operations. These commands and operations include:
  • Set
  • Add
  • Replace
  • Get
  • Delete
The first three commands are standard modification commands used to operate key-value pairs stored in memcached. They are easy to use.
3.3.1 modify command syntax
command <key> <flags> <expiration time> <bytes>
<value>
 

Modify the parameters and usage of the memcached command.

Parameters

Usage

Key

Key is used to find the cache value.

Flags

It can include an integer parameter of a key-value pair. The client uses it to store additional information about the key-value pair.

Expiration time

The duration of saving the key-value pair in the cache (in seconds, 0 indicates permanent)

Bytes

Byte points stored in the cache

Value

Stored value (always in the second row)

Now let's take a look at the actual use of these commands.

Set
setCommand to add a new key-value pair to the cache. If the key already exists, the previous value is replaced.

Note the following interactions:setCommand:

set userId 0 0 5
12345
STORED

If you usesetThe command correctly sets the key-value pair, and the server uses the wordSTORED. In this example, a key-value pair is added to the cache, whose key isuserIdThe value is12345. And set the expiration time to 0, which will notify memcached that you want to store this value in the cache until you delete it.

Add
If no key exists in the cache,addCommand to add a key-value pair to the cache. If a key already exists in the cache, the previous values remain the same and you will get a responseNOT_STORED.

UseaddStandard interaction of commands:

set userId 0 0 5
12345
STORED
 
add userId 0 0 5
55555
NOT_STORED
 
add companyId 0 0 3
564
STORED

Replace
Only when the key already exists,replaceCommand to replace the key in the cache. If no key exists in the cache, you will receiveNOT_STOREDResponse.

UsereplaceStandard interaction of commands:

replace accountId 0 0 5
67890
NOT_STORED
 
set accountId 0 0 5
67890
STORED
 
replace accountId 0 0 5
55555
STORED

The last two basic commands are:getAnddelete. These commands are quite easy to understand and use similar syntax, as shown below:

command <key>

Next, let's look at the application of these commands.

Get
getThe command is used to retrieve values related to the previously added key-value pair. You will usegetPerform most search operations.

UsegetTypical interaction of commands:

set userId 0 0 5
12345
STORED
 
get userId
VALUE userId 0 5
12345
END
 
get bob
END

As you can see,getThe command is quite simple. You use a key to callgetIf the key exists in the cache, the corresponding value is returned. If no content exists, NO content is returned.

Delete
The last basic command is delete. The delete command is used to delete any existing values in memcached. You will use a key to call delete. If the key exists in the cache, the value is deleted. If it does not exist, returnNOT_FOUNDMessage.

UsedeleteCommand client server interaction:

set userId 0 0 5
98765
STORED
 
delete bob
NOT_FOUND
 
delete userId
DELETED
 
get userId
END
3.4 advanced memcached client commands

The two advanced commands that can be used in memcached are gets and cas. The gets and cas commands must be used in combination. You will use these two commands to ensure that the existing name/value pairs are not set as new values (if the value has been updated ). Let's look at these commands separately.

3.4.1 , Gets

The gets command function is similar to the basic get command. The difference between the two commands is that gets returns a little more information: the 64-bit integer value is very similar to the "version" identifier of the name/value pair.

UsegetsCommand client server interaction:

set userId 0 0 5
12345
STORED
 
get userId
VALUE userId 0 5
12345
END
 
gets userId
VALUE userId 0 5 4
12345
END

ConsiderationsgetAndgetsDifferences between commands.getsThe command returns an additional value-in this example, integer value 4 is used to identify the name/value pair. If you execute anothersetCommand, thengetsThe returned additional value is changed to indicate that the name/value pair has been updated. Listing 6 shows an example:

3.4.2 , Set Update version indicator
set userId 0 0 5
33333
STORED
 
gets userId
VALUE userId 0 5 5
33333
END

You can seegetsIs the returned value? It has been updated to 5. This value is changed every time you modify the name/value pair.

3.4.3 , Cas

cas(Check and set) is a very convenient memcached command, used to set the value of the name/value pair (if this name/value pair is executed on your lastgets). It usessetSyntax similar to the command, but includes an additional value:getsThe returned additional value.

Note the following:casCommand Interaction:

set userId 0 0 5
55555
STORED
 
gets userId
VALUE userId 0 5 6
55555
END
 
cas userId 0 0 5 6
33333
STORED

As you can see, I use an additional integer value of 6 to callgetsCommand, and the operation runs in a very sequential order. Now let's take a look at a series of commands in listing 7:

3.4.4. casCommand
set userId 0 0 5
55555
STORED
 
gets userId
VALUE userId 0 5 8
55555
END
 
cas userId 0 0 5 6
33333
EXISTS

Note: I have not usedgetsAndcasCommand to return the EXISTS value to indicate failure. In essencegetsAndcasCommand to prevent you from using the name/value pair that has been updated since the last read.

3.4.5 Cache Management commands

The last two memcached commands are used to monitor and clear memcached instances. They arestatsAndflush_allCommand.

Stats

statsThe command function is called to dump the current statistics of the connected memcached instance. In the following example, runstatsCommand displays information about the current memcached instance:

Most outputs here are easy to understand. I will explain the meanings of these values in detail when discussing cache performance later. For the moment, let's take a look at the output and then use the new key to run somesetCommand and run it againstatsCommand, pay attention to the changes.

Flush_all

flush_allIs the last command to be introduced. This simplest command is only used to clear all name/value pairs in the cache. If you need to reset the cache to a clean stateflush_allCan provide a lot of use. Below is a usageflush_allExample:

set userId 0 0 5
55555
STORED
 
get userId
VALUE userId 0 5
55555
END
 
flush_all
OK
 
get userId
END
3.5 cache Performance

At the end of this article, I will discuss how to use the advanced memcached command to determine the cache performance.statsCommand for Cache Optimization. The two most important statistics are et_hits and get_misses. These two values indicate the number of times (get_hits) of finding the name/value pair and the number of times (get_misses) of not finding the name/value pair ).

With these values, we can determine the cache utilization. When starting the cache for the first time, we can see that get_misses will naturally increase, but after a certain amount of use, these get_misses values should gradually become stable-This indicates that the cache is mainly used for common read operations. If you see that get_misses continues to increase rapidly and get_hits gradually becomes stable, you need to determine what the cached content is. You may have cached the error content.

Another way to determine the cache efficiency is to view the cache hit rate (hit ratio ). Cache hit rate indicates executiongetTimes and missedgetThe percentage of times. To determine this percentage, run it againstatsCommand

3.5.1 calculate cache hit rate

Now, divide the value of get_hits by pai_gets. In this example, your hit rate is about 71%. Ideally, you may want a higher percentage-the higher the ratio, the better. View statistics and measure them from time to determine the efficiency of cache policies.

4 C # available clients

C # There are four types of available clients. Each client API has detailed descriptions and annotations.

  • . NET memcached client libraryHttps://sourceforge.net/projects/memcacheddotnet/
  • EnyimMemcachedHttp://www.codeplex.com/EnyimMemcached/-Client developed in. NET 2.0 keeping performance and extensibility inmind. (Supports consistent hashing .)
  • BeitmemcachedH. NET memcached client library http://code.google.com/p/beitmemcached/-Client developed by BeIT with newer features

Composite: couchbase + EnyimMemcached http://www.couchbase.com/

4.1. Available client memcached client library in C #

There is an example of Cookie + Memcached simulating Session log-on status. The running condition is that the computer needs to install the mysql database and configureAdd a link string and replace the username and password with your own.

<Add

Name = "MySqlDemo" connectionString = "server = 127.0.0.1; user id = root; password = 123; persist securityinfo = True; database = MySqlDemo; charset = utf8;" providerName = "MySql. data. mySqlClient "/>

Reprinted from: http://www.cnblogs.com/Blogs-Wang/p/4453215.html

 

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.