redis内存型数据库,内存远远快于硬盘
基于内存进行查询、存储操作,处理速度远快于Mongodb与Mysql
1、redis基本数据结构都是键值对形式、非关系型数据库
2、支持数据持久化
3、可以支持复杂数据结构的存储
4、单个操作都是原子性(多个操作也支持事务实现原子性)
redis基本数据结构
1、string
为动态字符串,根据实际情况动态调整字符大小
SET name chenwuyou
GET name
2、list
rpush/lpush 操作队列,使用lpop和rpop出队列
使用方式:
LPUSH dbs redis
LPUSH dbs mongodb
LPUSH dbs mysql
LRANGE dbs 0 -1
3、set
Redis 的set是string类型的无序集合,集合成员是唯一的,redis中集合通过哈希实现,添加,删除,查找的复杂度都是O(1)
SADD dbs_set redis
SADD dbs_set mongodb
SADD dbs_set mysql
SMEMBERS dbs_set
4、hash
HMSET me name “chenwuyou” age 30 hobby “code”
HGETALL me
5、zset
有序集合
ZADD dbs_zset 1 redis
ZADD dbs_zset 2 mongodb
ZADD dbs_zset 3 mysql
ZRANGE dbs_zset 0 -1
‘’’
import redis as pyredis
myredis = pyredis.StrictRedis(
connection_pool = pyredis.ConnectionPool(
host = 'localhost',
port = 6379,
db = 0,
encoding = 'utf8',
decode_responses = True
)
)
myredis.set('name','chenwuyou')
print(myredis.get('name'))
使用pipeline
pipe = myredis.pipeline()
pipe.hset('learn','redis',1)
pipe.hset('learn','mongodb',2)
pipe.hset('learn','mysql',3)
pipe.execute()
pipe.close()
key = 'mydbs'
dbs = ['redis','mongodb','mysql']
with myredis.pipeline() as pipe:
for score,db in enumerate(dbs):
pipe.zadd(key,{db:score})
pipe.execute()
result = myredis.zrange(key,0,-1)
print(result)
#分布式锁,保证在同一时间下只能有一个客户端对共享资源进行操作
def redislock(key):
return myredis.lock(key,blocking_timeout=30,timeout=30)
key = 'redis_lock'
with redislock(key):
print('分布锁')