python redis基本操作
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 # author:Lenovo 4 # datetime:2019/4/24 16:26 5 # software: PyCharm 6 import redis 7 #链接服务器 8 config={"host":"127.0.0.1","port":6379,'password':'leo@0362','db':0}#没有密码password 可不写 db 数据库 9 #方式一 10 #client=redis.Redis(**config) 11 #print(client.ping()) 12 #方式二 给配置文件增加链接池数 13 config['max_connections']=100 14 pool=redis.ConnectionPool(**config) 15 client=redis.Redis(connection_pool=pool) 16 print(client.ping())#是否链接成功 17 print(dir(client))#查看所有的方法属性 18 print(client.keys('*'))#查看数据库0 下所有keys 19 client.execute_command('select 1') #选择数据库 1 20 print(client.keys('*')) #查看数据库1 下所有keys 21 #String 字符串操作 22 #set(name, value, ex=None, px=None, nx=False, xx=False) 在Redis中设置值 23 #print(help(client.set))#查看set 的帮助信息 24 # 参数: 25 # ex,过期时间(秒) 26 # px,过期时间(毫秒) 27 # nx,如果设置为True,则只有name不存在时,当前set操作才执行 28 # xx,如果设置为True,则只有name存在时,岗前set操作才执行 29 print(client.set('leos','世界你好')) #返回 True 30 #get get(name) method of redis.client.Redis instance Return the value at key ``name``, or None if the key doesn't exist 返回 beyt 类型 31 #print(help(client.get)) 32 print(client.get('leos').decode('utf-8'))#世界你好 33 client.setnx('ok','世界你好')#只有ok 不存在时候才会赋值 34 client.setex('nihao',60,'没有更')#设置你好过期时间60秒 35 client.psetex('nihaos',600,'hehoa')#设置你好是 过期是时间600毫秒 36 client.mset({'a':'10','b':'20'})#批量设置值 37 print(client.mget('a','b'))#批量获取 38 print(client.mget(('a','b')))#批量获取 39 print(client.getset('leos','hello word').decode())#设置新值,并返回原来的值 40 print(client.strlen('leos'))#返回leos 的长度,汉字三个字节 41 print(client.incr('a',amount=2))#将a的值自增2 amount 默认为1 42 print(client.incrbyfloat('b',amount=0.2))#自增浮点数 43 print(client.get('b')) 44 print(client.decr('a',amount=3))#将a的值自减2 amount 默认为1 45 print(client.get('a')) 46 print(client.append('leos',' ok'))#追加内容

更多精彩