First, build memcached and Redis
Go to Baidu yourself.
Second, Operation Mmecached
1. Install the API
python-m pip Install python-memcached
2. Start memcached
memcached-d-u root-p 12000-m-d-u root-p 12001-m 50-d-u root-p 12002-m
参数说明:
-
d 是启动一个守护进程
-
m 是分配给Memcache使用的内存数量,单位是MB
-
u 是运行Memcache的用户
-
l 是监听的服务器IP地址
-
p 是设置Memcache监听的端口,最好是
1024
以上的端口
-
c 选项是最大运行的并发连接数,默认是
1024
,按照你服务器的负载量来设定
-
P 是设置保存Memcache的pid文件
3. Python memcached module support for memcached clusters
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.
1234567 |
主机 权重
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"
, ]
|
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:
123 |
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‘
)
|
4. Add (KeyName, value)
Obj.add (' K1 ', ' v1 ') obj.add (' K1 ', ' v1 ') v1 = obj.get (' K1 ') print (' v1: ', v1) out:MemCached:while expecting ' STORED ', got une xpected response ' not_stored ' # If the added key exists, then the error v1: v1
5. Replace (KeyName, New_value)
Obj.replace (' K1 ', ' new_v1 ') v1 = obj.get (' K1 ') print (' v1: ', v1) out:v1: new_v1
6. Set and Set_multi
Set sets a key-value pair, if key does not exist, is created if key exists, then modifies
Get gets a key value pair
Set_multi set multiple key-value pairs, if key does not exist, create if key exists, modify
Get_multi getting multiple key-value pairs
# Set and get
Obj.set (' K1 ', ' modify_v1 ') obj.set (' K2 ', ' newadd_v2 ') v1 = obj.get (' K1 ') print (' v1: ', v1) v2 = obj.get (' K2 ') print (' V2: '), V2) Out:v1: modify_v1v2: newadd_v2
# Set_multi and Get_multiobj.set_multi ({' K3 ': ' V3 ', ' K4 ': ' v4 '}) print (Obj.get_multi ([' K3 ', ' K4 ')]) out:{' K3 ': ' V3 ', ' K4 ': ' V4 '}
7. Delete and Delete_multi
9. Append and Prepend
DECR and INCR.
One. Gets and CAs
Python Beginner's way: Python Basics-Operation Cache Memcache, Redis