memcache安装:
Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值的hashmap。其守护进程(daemon)是用C语言写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。
wget http://memcached.org/latest
mv memcached-1.5.3.tar.gz /root/package/
cd /root/package/
tar -zxvf memcached-1.5.3.tar.gz -C /usr/local/src/
cd /usr/local/src/memcached-1.5.3/
yum -y install libevent* --skip-broken \\这里报错:安装memcache出现configure: error: libevent is required. If it's already installed, specify its path using –with-libevent=/dir/,这样解决。
./configure --prefix=/usr/local/memcached
make && make test && make install
启动memcache服务:
[root@localhost bin]# ./memcached -d -m 10 -u root -l 127.0.0.1 -p 11211 -c 256 -P /usr/local/src/memcached-1.5.3/logs/memcache.pid
[root@localhost bin]# ps -ef | grep memcache
root 16911 1 0 20:56 ? 00:00:00 ./memcached -d -m 10 -u root -l 127.0.0.1 -p 11211 -c 256 -P /usr/local/src/memcached-1.5.3/logs/memcache.pid
root 16922 3016 0 20:56 pts/0 00:00:00 grep memcache
[root@localhost bin]# netstat -anpt | grep memcache
tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN 16911/./memcached
[root@localhost bin]# pwd
/usr/local/memcached/bin
-p 指定端口号(默认11211)
-m 指定最大使用内存大小(默认64MB)
-t 线程数(默认4)
-l 连接的IP地址, 默认是本机
-d 以后台守护进程的方式启动
-c 最大同时连接数,默认是1024
-P 制定memecache的pid文件
对memcache实际操作:
[root@localhost memcached-1.5.3]# telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
add test 1 0 5 \\add添加数据,过期时间为0,长度是5(下面的hello长度是5)。
hello
STORED \\表示成功写入一条数据。
memcache群集操作:
C:\pip-9.0.1>pip install python-memcached \\一定要使用这个语句进行安装。
安装了python-memcache才能在pycharm中import memcache。
#@File :memcache_qunji.py #安装memcache客户端:pip install memcache import memcache mc = memcache.Client([("192.168.172.20:11211", 1), ("192.168.172.20:11212", 2), ("192.168.172.20:11213", 1)], debug=True) mc.set("k1", "v1") print(mc.get("k1")) mc1 = memcache.Client([("192.168.172.20:11211")], debug=True) \\memcache.Client初始化一个memcache的客户端对象 print(mc1.get("k1")) mc2 = memcache.Client([("192.168.172.20:11212")], debug=True) print(mc2.get("k1"))v1
None
v1
下面来看一个例子,python操作memcache集群
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')
如果用户要在内存中创建一个键值对(如:k1 = “v1”),那么要执行以下步骤:
根据算法将k1转换成一个数字;
将数字和主机列表长度求余数,得到一个值N(0 <= N < 列表长度);
在主机列表中根据第2步得到的值为索引获取主机,例如:host_list[N];
连接将第3步中获取的主机,将k1 = 'v1'放置在该服务器的内存中。
上面例子我们通过调用memcache模块来实现对memcached进行存取数据,debug=True表示运行中出现错误时,显示错误信息,上线后移除该参数。