后台小程序开发的全方位指南
919
2022-10-08
pythonNote033---操作Redis
Intro
关注点:
目前只看hashset内容增改删除常规操作就可类似mysql,怎么减少长连接的操作
增改删查
import
db = redis.Redis(host='127.0.0.1', port=6379, password='12345', db=0, encoding='utf-8', decode_responses=True) #password='12345',
库下key数量
db.dbsize()
1
增
db.hset(name="student",mapping={"name":"jack","sex":"male","score":90})
3
db.dbsize()
1
查
查指定field
db.hget(name="student",key="name")
'jack'
db.hget(name="student",key="score")
'90'
查询时,name是key,key相当于field。python这个为啥不和原生命令保持一致?
查所有field
db.hgetall("student")
{'name': 'jack', 'sex': 'male', 'score': '90'}
field数量
db.hlen("student")
3
改
修改指定field值
db.hset(name="student",key="score",value=100)db.hgetall("student")
{'name': 'jack', 'sex': 'male', 'score': '100'}
修改or覆盖原来的key
db.hset(name="student",mapping={"name":"jack","sex":"male","score":990})db.hgetall("student")
{'name': 'jack', 'sex': 'male', 'score': '990'}
删
db.delete("student")db.dbsize()
0
Redis的其他操作
db.dbsize()
0
设置过期时间
db.hset(name="student:jack",mapping={"sex":"male","score":70})db.expire("student:jack",60)db.hset(name="student:leo",mapping={"sex":"male","score":80})db.expire("student:leo",200)db.hset(name="student:marry",mapping={"sex":"female","score":90})db.expire("student:marry",600)db.dbsize()
3
查看所有key
db.keys()
['student:jack', 'student:marry', 'student:leo']
查询剩余生存时间
ttl key 以秒为单位返回key的剩余生存时间(time to live),当key不存在时返回-2,当key存在未设置生存时间时返回-1
db.ttl("student:jack")
-2
db.ttl("student:leo")
195
db.close()
批量写入redis
所谓连接池的操作,更常规的是不是批量写入,每次写入的时候连接即可? 先记录一下
import datetimedef timer(start_time=None): if not start_time: start_time = datetime.datetime.now() return start_time elif start_time: thour, temp_sec = divmod((datetime.datetime.now() - start_time).total_seconds(), 3600) tmin, tsec = divmod(temp_sec, 60) print('\n Time taken: %i hours %i minutes and %s seconds.' % (thour, tmin, round(tsec, 2)))
直接连接
start_time = timer()db = redis.Redis(host='127.0.0.1', port=6379, password='12345', db=0, encoding='utf-8', decode_responses=True) for i in range(0,100000): db.hset(name="student:"+str(i),mapping={"name":"jack","sex":"male","score":90})timer(start_time)db.close()
Time taken: 0 hours 0 minutes and 14.03 seconds.
for i in db.keys():db.delete(i)
start_time = timer()pool=redis.ConnectionPool(password='12345')db = redis.Redis(connection_pool=pool, host='127.0.0.1', port=6379,# password='12345', db=0, encoding='utf-8', decode_responses=True) for i in range(0,100000): db.hset(name="student:"+str(i),mapping={"name":"jack","sex":"male","score":90})timer(start_time)db.close()
Time taken: 0 hours 0 minutes and 16.18 seconds.
单次写入好像没啥差别,查询时候有差别吧,不用每次查询都连接?先不管了,后面用到再说
Ref
[2] https://redis.com-/redis-installation.html
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~