Memcached of the cache

Source: Internet
Author: User
Tags cas memcached

Memcached

Memcached is a high-performance distributed memory object caching system for dynamic Web applications to mitigate database load. It improves the speed of dynamic, database-driven Web sites by caching data and objects in memory to reduce the number of times a database is read. Memcached is based on a hashmap that stores key/value pairs. Its daemon (daemon) is written in C, but the client can write in any language and communicate with the daemon through the Memcached protocol

memcached installation and Basic use

Memcached Installation:

wget http://memcached.org/latesttar-zxvf memcached-1.x.x.tar.gzcd memcached-1.x.x./configure && Make & & make Test && sudo make install PS: dependent libevent       yum install libevent-devel       apt-get Install Libevent-de

Start memcached

Memcached-d-M-    u root-l 10.211.55.4-p 12000-c 256-p/tmp/memcached.pid parameter Description:-    D is the start of a daemon-    m is assigned to MEMC Ache the amount of memory used, in MB-    U is the user running Memcache-    L is the listening server IP address-    p is setting the Memcache listening port, preferably more than 1024 port-    C option is the maximum number of concurrent connections running, default is 1024, according to the load on your server to set-    p is set to save memcache PID file

Python Operation memcached

Install API

Python operation memcached Download the installation using the Python-memcached module: https://pypi.python.org/pypi/python-memcached

1. First operation

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) mc.set ("foo", "bar") ret = mc.get (' foo ') print (ret)

Ps:debug = True indicates a real-world error message when running an error, removing the parameter when it goes live

2, Natural support cluster

The python-memcached module natively supports cluster operations by maintaining a list of hosts in memory, and the weight values of the hosts in the cluster are proportional to the number of occurrences of the host in the list.

Import MEMCACHEMC = Memcache. Client ([' 123.206.96.209:12090 ', 2), #其中2表示的是权重, both the number of                       ' 123.206.96.209:12091 ',                       ' 123.206.96.209:12092 ',                       ' 123.206.96.209:12093 '],debug=true,cache_cas=true) mc.set (' K1 ', ' v1 ') #集群中有许多用于缓存的主机, when we set the value, Memcache will convert the ' K1 ' to the number 5646 according to the following # algorithm, then 5464 divided by the number of hosts to get the remainder 4, and then according to the index # selection should be placed in that cache, get the same time import Binasciidef Cmemcache_hash (key):    Return ((((        binascii.crc32 (Key & 0xFFFFFFFF)          >>) & 0x7fff) or 1) R = Cmemcache_hash ( Bytes (' K1 ', encoding= ' utf-8 '))

If the user is to create a key-value pair in memory (for example: K1 = "V1"), then perform the steps:

    • Convert K1 into a number based on the algorithm
    • Calculate number and host list length to remainder, get a value n (0 <= N < list length)
    • Gets the host in the host list according to the value obtained in 2nd step, for example: Host_list[n]
    • Connect the host acquired in step 3rd, place k1 = "V1" In the server's memory

3. Add

Add a key value pair, and if the key already exists, repeat the Add operation exception Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) mc.add (' K1 ', ' v1 ') mc.add (' K1 ', ' v2 ') # error, repeat add to existing key, FAIL!!!

4. Replace

Replace modifies the value of a key, and if key does not exist, the exception is import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) # If KKKK is present in Memcache, the substitution succeeds, otherwise the exception mc.replace (' Kkkk ', ' 999 ')

5. Set and Set_multi

Set sets a key-value pair, if key does not exist, is created if key exists, then modifies
Set_multi set multiple key-value pairs, if key does not exist, create if key exists, modify

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) mc.set (' Key0 ', ' Wupeiqi ') mc.set_multi ({' Key1 ': ' Val1 ', ' key2 ': ' Val2 '})

6. Delete and Delete_multi

Delete Deletes a specified key-value pair in memcached
Delete_multi Delete a specified number of key-value pairs in memcached

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) mc.delete (' Key0 ') mc.delete_multi ([' Key1 ', ' Key2 '])

7. Get and Get_multi

Get gets a key value pair
Get_multi get more than one key-value pair

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) val = mc.get (' key0 ') item_dict = Mc.get_multi (["Key1", "Key2", "Key3"])

8, Append and prepend

Append modifies the value of the specified key, appending the content after the value
Prepend Modify the value of the specified key to insert the contents before the value

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) # k1 = "V1" mc.append (' K1 ', ' after ') # K1 = "V1after" mc.prepend (' K1 ', ' before ') # K1 = "Beforev1after"

9, DECR and INCR

INCR increment, add a value in memcached n (n default = 1)
DECR, reducing a value in memcached by n (n default = 1)

Import MEMCACHEMC = Memcache. Client ([' 10.211.55.4:12000 '], debug=true) mc.set (' K1 ', ' 777 ') mc.incr (' K1 ') # K1 = 778mc.incr (' K1 ', ten) # K1 = 788MC.DECR (' K1 ') # K1 = 787mc.decr (' K1 ', ten) # K1 = 777

10, gets and CAS (prevent dirty data from happening)

such as the number of goods in the mall, assuming that the change is stored in memcache, Product_count = 900
A user Refresh page reads from memcache to Product_count = 900
b User Refresh page read from memcache to Product_count = 900

If both A and B users purchase goods

A user modified the number of items remaining product_count=899
b User modified the number of items remaining product_count=899

As a result, the data in the cache is not correct, two users after the purchase of goods, the product surplus or 899
If you use Python's set and get to manipulate the above procedure, the program will look like the above situation!

If you want to avoid this situation, just use get and CAS, such as:

Import MEMCACHEMC = Memcache. Client ([' 123.206.96.209:12000 '],debug=true,cache_cas=true)  #必须加cache_cas =truemc.set (' Product_count ', ') v = Mc.gets (' Product_count ') print (v) print (input (' >>>>> ')) Mc.cas (' Product_count ', "899") #同时运行俩个这样的程序, All get to a value corresponding to a product_count, when one of the program points returns to both modify the value of Product_count, another program also point to enter the time will be error, error message: #MemCached: While expecting ' STORED ', got unexpected response ' EXISTS '

  

Memcached of the cache

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.