Python Operation memcached

Source: Internet
Author: User
Tags cas

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.

install memcached under Linux

Memcached, poke me.

Installing Libeventtar zxf libevent-2.0.22-stable.tar.gz CD libevent-2.0.22-stable./configure--prefix=/usr/local/ Libeventmake make install Memcachedtar zxf memcached-1.4.36.tar.gz CD memcached-1.4.36./configure--prefix=/usr/ Local/memcache--with-libevent=/usr/local/libevent/make make Installln-s/usr/local/memcache/bin/*/usr/local/bin/

Start memcached

Memcached-m 32m-p 11211-d-u root-p/var/run/memcache.pid-c 256 parameter description:    -D is to start a daemon-    m is allocated to the amount of memory used by memcache, in units of MB-    U is the user that is running memcache-    L is the server IP address of the listener-    p is the port that sets Memcache listening, preferably more than 1024 of the port-    C option is the maximum number of concurrent connections running, the default is 1024, According to the load of your server to set-    p is set to save memcache PID file

Connect memcached using Telnet

Telnet 192.168.56.102 11211

MEMCAHCE's command and more, poke me

Using Python to manipulate 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 ([' 192.168.56.102:11211 '], debug=true) mc.set ("foo", "bar") ret = mc.get (' foo ') print ret

Ps:debug = True indicates a real-world error message when a run error occurs, and the parameter is removed when it is online.

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.

     Host            weight    192.168.56.102   1    192.168.56.103   2    192.168.56.104   1 then in-memory host list is:    host_ List = ["192.168.56.102", "192.168.56.103", "192.168.56.104", "192.168.56.105",]

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

The code is implemented as follows:

MC = Memcache. Client ([' 192.168.56.102:11211 ', 1), (' 192.168.56.103:11211 ', 2), (' 192.168.56.104:11211 ', 1)], debug=true) mc.set (' K1 ', ' v1 ')

3. Add
Add a key-value pair, repeat the add operation exception if the key already exists

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.10.102:11211 '], debug=true) mc.add (' K1 ', ' v1 ') # mc.add (' K1 ', ' v2 ') # error, added to the existing key repeatedly, failed!!!

4. Replace
Replace modifies the value of a key, and if key does not exist, the exception

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.10.102:11211 '], debug=true) # If KKKK is present in Memcache, the substitution succeeds, otherwise a 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

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.10.102:11211 '], debug=true) mc.set (' key ', ' Musker ') 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

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.10.102:11211 '], debug=true) mc.delete (' key ') 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

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 102.168.56.102:11211 '], debug=true) val = mc.get (' key ') 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

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.56.102:11211 '], 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)

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.56.102:11211 '], 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

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:

#!/usr/bin/env python#-*-coding:utf-8-*-import memcachemc = memcache. Client ([' 192.168.56.102:11211 '], debug=true, cache_cas=true) v = mc.gets (' Product_count ') # ... # If someone modifies the product_count after the get and the CAs, the following settings will fail to be performed, splitting out the exception, thus avoiding Mc.cas (' Product_count ', "899") of abnormal data

Ps: In essence, each time a get is executed, it gets a self-increment number from the memcache, and when the value of the get is modified by CAS, it is compared with the self-increment value obtained before and memcache, if it is equal, it can be submitted, if not, That means that between get and CAS execution, there are other people who perform the gets (the specified value of the buffer is obtained), so that if abnormal data is possible, no modification is allowed.

Python Operation memcached

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.