目录
redis 基本命令 String
基础操作
定时key
是否操作
nx
xx
redis 基本命令 String
set(name, value, ex=None, px=None, nx=False, xx=False)
在 Redis 中设置值,默认,不存在则创建,存在则修改。
参数:
- ex - 过期时间(秒)
- px - 过期时间(毫秒)
- nx - 如果设置为True,则只有name不存在时,当前set操作才执行
- xx - 如果设置为True,则只有name存在时,当前set操作才执行
基础操作
创建【demo2.py】进行案例测试
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('StrKey', 'I Have A Dream!')
print(r.get('StrKey'))

效果:
?
这是字符串的基础操作。
定时key
ex - 过期时间(秒) 这里过期时间是60秒,60秒后StrKey的值就变成None
px - 过期时间(毫秒)与ex一样的就是单位不同,操作一样。
import redis
import time
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('StrKey', 'I Have A Dream!',ex=3)
print(r.get('StrKey'))
print("倒计时:3")
time.sleep(1)
print("倒计时:2")
time.sleep(1)
print("倒计时:1")
time.sleep(1)
print(r.get('StrKey'))

是否操作
nx
nx - 如果设置为True,则只有name不存在时,当前set操作才执行
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('StrKey','Info')
print(r.set('StrKey', 'testInfo', nx=True))
#如果键 StrKey 不存在,那么输出是True;如果键 StrKey 已经存在,输出是None

xx
xx - 如果设置为True,则只有name存在时,当前set操作才执行 (修改)
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.set('StrKey','Info')
print((r.set('StrKey', 'testInfo', xx=True)))
print((r.set('StrKey1', 'testInfo', xx=True)))
由于KeySet存在,故而操作了,输出【True】
由于KeySet1不存在,故而未操作,输出【None】?

?
|