使用Python读写Redis——Strings

之前详细介绍了Redis命令 - Strings命令组常用命令,同样的命令,本文将用python调用redis库封装好的方法。

1、Python连接redis

import redis
from config.VAR import INT_REDIS_HOST, INT_REDIS_PORT, INT_REDIS_PASSWORD

# 便于修改,将redis的连接配置在VAR.py中,管理这些常量
r = redis.StrictRedis(host=INT_REDIS_HOST, port=INT_REDIS_PORT, password=INT_REDIS_PASSWORD, db=6, ssl=False)

2、SET key value

# SET key value
# 创建一个key,过期时间默认是-1(永久有效)
print(r.set("mystring", "zhangsan"))  # True
print(r.get("mystring"))  # b'zhangsan'

3、SET key value nx

# SET key value nx
# 当此key不存在时,才创建这个key,并设置key值
print(r.set("mystring", "zhangsan", nx=True))  # None
print(r.get("mystring"))  # b'zhangsan'

4、SET key value xx

# SET key value xx
# 当此key存在时,才设置key值
print(r.set("mystring", "lisi", xx=True))  # True
print(r.get("mystring"))  # b'lisi'

5、SET key value [EX seconds] 或者 SETEX key seconds value

# 设置key的过期时间,秒
# 方式一:SET key value [EX seconds]
print(r.set("mystring", "lisi", ex=10))  # True
# 方式二:SETEX key seconds value
# print(r.setex("mystring", 10, "lisi"))
print(r.get("mystring"))  # b'lisi'
time.sleep(10)
print(f"过了10s后再查询key, 返回值:{r.get('mystring')}")  # None

6、SET key value [PX milliseconds] 或者 PSETEX key time_ms value

# 设置key的过期时间,1000毫秒
# 方式一:SET key value [PX milliseconds]
print(r.set("mystring", "lisi", px=1000))  # True
# 方式二:PSETEX key time_ms value
# print(r.psetex("mystring", 1000, "lisi"))
print(r.get("mystring"))  # b'lisi'
time.sleep(1)
print(f"过了1s后再查询key, 返回值:{r.get('mystring')}")  # None

7、GETSET

# getset
# 赋新值取旧值
print(r.set("mystring", "zhangsan"))  # True
print(r.get("mystring"))  # b'zhangsan'
print(r.getset("mystring", "wangwu"))  # b'zhangsan'
print(r.get("mystring"))  # b'wangwu'

8、INCR key 和 INCRBY key increment

# INCR key
# amount默认是1
print(r.set("myno", "123"))  # True
print(r.incr("myno"))  # 124
# INCRBY key amount
print(r.incrby("myno", 100))  # 224

9、DECR key 和 DECRBY key decrement

# DECR key
# amount默认是1
print(r.set("myno", "200"))  # True
print(r.decr("myno"))  # 199
# DECRBY key amount
print(r.decrby("myno", 200))  # -1

10、MSET key value [key, value]

# MSET key value [key, value]
print(r.mset({"user": "zhangsan", "pwd": "123456"}))  # True
print(r.get("user"))  # b'zhangsan'
print(r.get("pwd"))  # b'123456'

11、APPEND key value

# APPEND key value
print(r.set("mystring", "wangwu"))  # True
print(r.get("mystring"))  # b'wangwu'
print(r.append("mystring", "234"))  # 9,返回的是追加后,字符串的长度
print(r.get("mystring"))  # b'wangwu234'
# key不存在,会创建key并追加值
print(r.append("mystring1", "234"))  # 3
print(r.get("mystring1"))  # b'234'

你可能感兴趣的:(Redis,python,redis,bootstrap)