Python Operation memcached

Source: Internet
Author: User
Tags cas memcached

Brief introduction

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.

Characteristics
Memcached, as a distributed cache server running at high speed, has the following characteristics.
· Simple protocol
· Libevent-based event handling
· Built-in memory storage mode
· Memcached distributed without communication with each other
· To improve performance, the data saved in memcached is stored in Memcached's built-in memory storage space. Because the data exists only in memory, restarting the memcached and restarting the operating system will cause all data to disappear. Additionally, when the content capacity reaches the specified value, the unused cache is automatically deleted based on the LRU (Least recently used) algorithm. The memcached itself is a server designed for caching, so there is not too much consideration for permanent data issues.

Installing memcached
wget http://memcached.org/latestmemcached-1.5.7. Tar.gztar zxf memcached-1.5.7. tar.gzcd memcached-1.5.7. /configure && make && make test && make install

Installing the memcached Python client

Pip Install python-memcached

Start memcached
Memcached-d-M 10-u root-l 127.0.0.1-p 12000-c 256-p/var/log/memcache/memcache.pid

Detailed parameters:
-P Specify port number (default 11211)
-m specifies the maximum amount of memory to use (default 64MB)
-T thread count (default 4)
-L connected IP address, default is native
-D starts with the daemon process
-c Maximum number of simultaneous connections, default is 1024
-P Develop memecache PID file
-H Printing Help information

Support Cluster

The PYTHON-MEMCACHD 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 weights
1.1.1.1 1
1.1.1.2 2
1.1.1.3 1

#那么在内存中主机列表为:
host_list=[' 1.1.1.1 ', ' 1.1.1.2 ', ' 1.1.1.2 ', ' 1.1.1.3 ',]

Python Operation Memcache Cluster
MC = Memcache. Client (['1.1.1.1:12000', 1), ('1.1.1.2:12000', 2), ('  1.1.1.3:12000', 1)], debug=True) mc.set ('K1' ' v1 ')

Memcache Common operations

Storage commands: Set, add, replace, append, prepend, CAs
Get command: Get, gets
Other commands: Delete, stats

Add method
ImportMEMCACHEMC= Memcache. Client (['192.168.48.128:11211'], debug=True)#mc.set ("foo", "Bar")#ret = mc.get ("foo")Mc.add ('K1','v1') Mc.add ('K1','v1')Print(ret)

Replace method

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

ImportMEMCACHEMC= Memcache. Client (['192.168.48.128:11211'], debug=True)#mc.set ("foo", "Bar")#ret = mc.get ("foo")Mc.add ('K1','v1')#mc.add (' K1 ', ' v1 ')#print (ret)Mc.replace ("K1","Hello")Print(Mc.get ("K1") Results: Hello

Set and Set_multi methods

Set: Sets a key-value pair, if key does not exist, is created if key exists, then modified;
Set_multi: Sets multiple key-value pairs, if key does not exist, is created and modified if key exists.

ImportMEMCACHEMC= Memcache. Client (['192.168.48.128:11211'], debug=True) Mc.set ("K10","V10") Mc.set_multi ({"K11":"v11","K12":"V12"})

The difference between the Set method and the Add method

Set = add + Replace

Delete and Delete_multi methods

Delete: Deletes a specified key-value pair in the memcached;
Delete_multi: Deletes the specified number of key-value pairs in memcached.

Import= memcache. Client (['192.168.48.128:11211'], debug=True)#  mc.set ("K10", "V10 ")#  mc.set_multi ({" K11 ":" V11 "," K12 ":" V12 "})#Mc.delete ("K10  ") mc.delete_multi (["k11""K12 "])

Get and Get_multi methods

Get: Gets a key value pair;
Get_multi: Gets multiple key-value pairs.

ImportMEMCACHEMC= Memcache. Client (['192.168.48.128:11211'], debug=True) Mc.set ("K10","V10") Mc.set_multi ({"K11":"v11","K12":"V12"}) Val= Mc.get ('K1')Print(val) item_dict= Mc.get_multi (['K11','K12'])Print(item_dict)

Append and Prepend methods

Append: Modifies the value of the specified key, appending the content after the value;
Prepend: Modifies the value of the specified key to insert the contents before the value.

ImportMEMCACHEMC= Memcache. Client (['127.0.0.1:12000'], debug=True) Mc.append ('K1',' After') Val1= Mc.get ('K1')Print(VAL1) mc.prepend ('K1','Brefore') Val2= Mc.get ('K1')Print(VAL2)#Results:V1afterafterbreforev1afterafter

Stats

View historical operations

Gets and CAs

Using a cache system to share data resources is bound to bypass the problem of data contention and dirty data (data clutter).
Suppose that the remaining number of a product in a mall is saved in memcache, Product_count = 900
A user Refresh page reads from Memecache to Product_count = 900
b User Refresh page read from Memecache to Product_count = 900
A, a, a user buys a product and modifies the value of Product_count
A modified, Product_count = 899
b after modification, Product_count = 899
However the correct number should be 898, the data is chaotic.
If you want to avoid this situation, you can use Get and CAs
Note: To add the Cache_cas parameter to the client

ImportMEMCACHEMC= Memcache. Client (['192.168.48.131'],cache_cas=True) Mc.set ('Count'," -")Print(Mc.gets ("Count"))#Mc.set ("Count", ' + ')result = Mc.cas ("Count"," About")Print(Result)Print(Mc.get ("Count"))

Summarize
ImportMEMCACHEMC= Memcache. Client (['192.168.48.136:12000'])Print(MC) Mc.set ("AAA","Hello World")Print(Mc.get ("AAA"))#set (key, value)#get (Key)#Repalce (Key, New_value)#set = add + replace ()#Delete (key)#Get_multi ([K1, K2, K3])#Delete_multi ([K1, K2, K3])#Set_multi ({"K1": "V1", "K2": "V2"})#Append (k, appendvalue)#prepend (k, Prependvalue)Mc.add ("Mctestadd","Nihaoma")Print(Mc.get ("Mctestadd")) Mc.append ("AAA","321")Print(Mc.get ("AAA")) Mc.prepend ("AAA","123")Print(Mc.get ("AAA"))Print(mc.stats)

Python action memcached

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.