对memcached的简单了解,之前写代码只偶尔会用到redis也没有复杂的操作,memcached也有必要了解一下。所以有了这篇
memcache
安装
sudo apt install memcached
yum install memcached -y
启动
systemctl start memcached
cd /usr/bin
/usr/bin/memcached -d -u memcached -p 11211 -m 64 -l 0.0.0.0
# -d daemon
# -u user
# -p port (11211)
# -m memory (64M)
# -l ip list
连接
telnet ip port
常用命令
set 在memcached中添加一个key value 如果key已经存在过,那么就替换,否则就添加
set key 0[是否压缩] 60 过期时间 7[字符长度]
set name 0 60 4
andy STORED
get username[key] 从memcached中获取一个数据,根据key来获取
get name
VALUE name 0 4
andy
END
add向memcached中添加数据,如果已经存在就添加失败,否则就添加
add name 0 60 4
andy STORED
add name 0 60 4
andy NOT_STORED
delete key 删除数据
set name 0 60 4
andy STORED delete name DELETED
get name
END
flush_all 删除memcached中所有的值
incr 相加,相加的必须都是数字类型,否则 无法相加,报错
set age 0 120 2
12 STORED
incr age 8
20
decr 相减
decr age 8
12
stats命令,查看状态
stats
STAT pid 58180
STAT uptime 1462
STAT time 1585363342
STAT version 1.4.15
STAT libevent 2.0.21-stable
STAT pointer_size 64
STAT rusage_user 0.010977
STAT rusage_system 0.098796
STAT curr_connections 5 # 当前有多少连接
STAT total_connections 6 # 总共多少连接
STAT connection_structures 6
STAT reserved_fds 20
STAT cmd_get 5 # 总共get多少次
STAT cmd_set 6 # 总共set多少次
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits # 1 命中次数
STAT get_misses 4
STAT delete_misses 0
STAT delete_hits 1
STAT incr_misses 0
STAT incr_hits 1
STAT decr_misses 0
STAT decr_hits 1
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 312
STAT bytes_written 161
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT bytes 70
STAT curr_items 1 # 当前有多少个元素
STAT total_items 7
STAT expired_unfetched 1
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 3
END
memcached默认最大连接1024
python 使用memcached
安装
pip install python-memcached
连接
import memcache
#如果要实现分布式在下面的列表中添加对应主机的ip:port
mc = memcache.Client(['192.168.16.8:11211'],debug=True)
mc.set('name', 'andy',120)
print(mc.get('name'))
mc.set_multi({'name':'jack','age':18,'telephone':110},time=120)
print(mc.get('age'))
mc.delete('telephone')
print(mc.get('telephone'))
mc.incr('age', 2)
print(mc.get('age'))
mc.decr('age', 3)
print(mc.get('age'))
andy
18
None
20
17
安全相关: * 使用-l参数设置为只有本地可以连接,这种方式会导致别的机器不能访问,达到安全的目的 * 使用防火墙,关闭11211端口,外面 不能访问
ufw enable # 开启防火墙
ufw disable # 关闭防火墙
ufw deny port # 关闭某个指定端口
ufw allow port 开启某个端口