数据库
首页 > 数据库> > Redis相关操作

Redis相关操作

作者:互联网

Redis

1 redis连接

import redis
# 01 基本连接方式
# r=redis.Redis(host="127.0.0.1",port=6379)
#
#
# r.set("age",99)
#
# print(r.get("age")) # b'99'


# 02 基于连接池连接
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)

2 .字符串操作

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)



# r.set("name","alex",5)

# print(r.get("name"))

# r.set("name","alex",nx=True)
# r.set("name","alex")


# 批量设置

# r.mset({'k1': 'v1', 'k2': 'v2'})

# 取值操作

# print(r.get("k2")) # b'v2'

# 批量取值

# print(r.mget(["k1","k2"])) # [b'v1', b'v2']


# print(r.getrange("name",0,2))

# r.setrange("name",3,"!!!")

# print(r.strlen("name"))


# r.incr("age",2)

# r.append("name","egon")
字符串操作

3. hash操作

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)

# 为字典增加单个键值对
# r.hset("infos","name2","alex2") # {'infos':{'name':'alex'}}
# print(r.hget("infos","name"))

# 增加多个键值对
# 推荐
r.hset('infos',mapping={"age":1000,"gender":"male"})
print(r.hgetall('infos'))

"""
# 不推荐,即将被弃用
# r.hmset("infos",{"age":1000,"gender":"male"})
# r.hmset("infos",{"age2":1000})

{
# 'infos':{'name':'alex','age':1000,'gender':'male'}
# }
"""

# 查
# print(r.hmget("infos",["name","age"])) # [b'alex', b'1000']
# print(r.hgetall("infos")) # {b'name': b'alex', b'age': b'1000', b'gender': b'male'}

# print(r.hlen("infos"))

# print(r.hkeys("infos")) # [b'name', b'age', b'gender']
# print(r.hvals("infos")) # [b'alex', b'1000', b'male']
#
# print(r.hexists("infos","names"))

# 删除元素
# r.hdel("infos","gender")
# print(r.hgetall("infos")) # {b'name': b'alex', b'age': b'1000'}

# 键所对的值自增(+2)
# r.hincrby("infos","age",2) #{b'name': b'alex', b'age': b'1004', b'name2': b'alex2', b'age2': b'1002'}
#
# print(r.hgetall("infos"))

# print(r.hscan_iter("infos"))
# #
# for i in r.hscan_iter("infos"):
#     # print(i) #  #返回元组

# 正则匹配
# r.hmset("abc",{"a1":"b1","a2":"b2","a3":"b3","x1":"y1"}) # 弃用
r.hset('abc',mapping={"a1":"b1","a2":"b2","a3":"b3","x1":"y2"})
print(r.hgetall('abc'))

for i in r.hscan_iter("abc",match="a*"):
    print(i)
View Code

4 .list

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)

# r.lpush("scores",56,78,99,65,34)

#r.rpush("new_scores",23,56,77)

# print(r.lrange("scores",0,-1)) # [b'34', b'65', b'99', b'78', b'56']
# print(r.lrange("new_scores",0,-1)) # [b'23', b'56', b'77']

# r.lpushx("scores",100)

# print(r.llen("scores"))

# r.linsert("scores","AFTER","34","44")

# r.lset("scores",1,98)

# r.lrem("scores",count=0,value=98)

# print(r.lrange("scores",0,-1))

# print(r.lpop("scores"))
# print(r.lrange("scores",0,-1))

# print(r.lindex("scores",3))


# print(r.lrange("scores",0,-1))
# print(r.lrange("scores",1,3))


# r.ltrim("scores",1,3)
# print(r.lrange("scores",0,-1))
View Code

5. set

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)



# r.sadd("score_set01",1,2,3,4,5,6,6)
# r.sadd("score_set02",4,5,6,7,8)


# print(r.smembers("score_set01"))
# print(r.smembers("score_set02"))
#
# print(r.scard("score_set01"))
# print(r.scard("score_set02"))
#
# print(r.sinter("score_set01","score_set02")) # 交集
# print(r.sunion("score_set01","score_set02"))  # 并集
# print(r.sdiff("score_set01","score_set02"))  # 差集
#
#
#
# print(r.sismember("score_set01",6))
# print(r.sismember("score_set01",7))

# print(r.spop("score_set01"))
# print(r.smembers("score_set01"))

# print(r.srandmember("score_set01",3))

# r.srem("score_set01",5)
# print(r.smembers("score_set01"))


# print(r.sscan_iter("score_set01"))
# for i in r.sscan_iter("score_set01"):
#     print(i)
View Code

6. sortset操作

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)


# r.zadd("z",{"n1":1,"n2":2,"n3":5,"n4":3})

# print(r.zscan("z"))
#
# print(r.zcard("z"))


# print(r.zcount("z",1,3))
# print(r.zcount("z",1,4))
# print(r.zcount("z",1,5))

# r.zincrby("z",2,"n3")
# print(r.zscan("z"))

# print(r.zrange("z",0,2))
# print(r.zrange("z",0,3))

# print(r.zscore("z","n4"))
# print(r.zrank("z","n4"))



# r.zrem("z","n2")

# r.zremrangebyrank("z",0,1)
# r.zremrangebyscore("z",1,7)
# print(r.zscan("z"))




# r.zadd("z1",{"n1":1,"n2":2,"n3":3,"x":100})
# r.zadd("z2",{"n3":4,"n5":5,"n6":6,"x":100})

# r.zunionstore("z3",("z1","z2"))
# print(r.zscan("z3"))

r.zinterstore("z4",("z1","z2"))
print(r.zscan("z4"))
View Code

7 其他操作

import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)

# print(r.keys(pattern="k*"))
# print(r.delete("naem"))
# print(r.keys())


# print(r.exists("name"))
# print(r.exists("naem"))


# r.expire("name",10)
# print(r.keys())
#
# print(r.randomkey())
#
# print(r.type("infos"))


for i in r.scan_iter(match="k*"):
    print(i)
View Code

7 redis连接池

# by gaoxin
import redis


pool = redis.ConnectionPool(host="127.0.0.1", port=6379, decode_responses=True, max_connections=10)


conn = redis.Redis(connection_pool=pool)


ret = conn.get("n1")
print(ret)
View Code

8 管道操作(事务操作)

# redis的事务操作
import redis
pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
conn = redis.Redis(connection_pool=pool)

pipe = conn.pipeline(transaction=True)
pipe.multi() # 开始事务
pipe.set('name', 'bendere')
pipe.set('role', 'sb')
pipe.execute()  #提交
# 注意:咨询是否当前分布式 redis 是否支持事务
print(conn.keys())

9 发布-订阅

pub.py

# by gaoxin
import redis

conn = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)


conn.publish("gaoxin333", "18")

sub.py

# by gaoxin

import redis

conn = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)

# 第一步 生成一个订阅者对象
pubsub = conn.pubsub()

# 第二步 订阅一个消息

pubsub.subscribe("gaoxin333")

# 创建一个接收

while True:
    print("working~~~")
    msg = pubsub.parse_response()
    print(msg)

其他

# redis的事务操作(python连接)

import redis
pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
conn = redis.Redis(connection_pool=pool)

pipe = conn.pipeline(transaction=True)
pipe.multi() # 开始事务
pipe.set('name', 'bendere')
pipe.set('role', 'sb')
pipe.execute()  #提交


1 redis 事务操作 (数据库直接操作)
set age 100
multi # 开启事务
set age 10
set a 20
exec  # 结束

discard  取消所有事务,也就是事务回滚

2 redis 设置有效时间
ex设置有效时间

conn.set(key, json.dumps(context), ex=60 * 30) # 30分钟

3常用命令:

1) 查看keys个数

keys *      // 查看所有keys
keys prefix_*     // 查看前缀为"prefix_"的所有keys

2) 清空数据库
flushdb   // 清除当前数据库的所有keys
flushall    // 清除所有数据库的所有keys
3)
del 'a'  删除单个

 

标签:name,Redis,redis,score,相关,print,操作,infos,pool
来源: https://www.cnblogs.com/huahuawang/p/14813809.html