redis server学习001

redis server学习001

一、简介:

redis是使用ANSIC语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 非关系型数据库,并提供多种语言的API。

经常会用作缓存,消息中间件的操作。

二、特点:

速度快,因为数据存在内存中

支持丰富数据类型,支持字符串,哈希表,列表,集合,有序集合

支持事务,操作都是原子性

丰富的特性:可用于缓存,消息,按key设置过期时间,过期后将会自动删除

三、python3连接redis server

1、 一般连接redis情况

from redis import Redis

# 实例化redis对象
r = Redis(host='localhost', port=6379, db=0, password='123456')
r.set('name1', 'zhangsan1')  # b'zhangsan'
name1 = r.get('name1')
print(name1)

这种情况连接数据库,对数据的存取都是字节类型,存取时还得转码一下,一般不推荐这种方法

2、 连接池连接redis

import redis

pool = redis.ConnectionPool(host='127.0.0.1', port=6379, password='123456', decode_responses=True)  # decode_response,默认值是False,如果我们把这个值改为True,则避免了转码流程(上述出现的字节类型的情况),直接对原数据进行操作。
r = redis.Redis(connection_pool=pool)
r.set('name2', 'zhangsan2')
print(r.get('name2'))  # b'zhangsan2'
r.close()

3、 pipeline模式

用来批量的提交命令,还用来实现事务transation。

能够将多条命令集中起来,一次发送到redis服务端,从而减少网络IO时延。

import redis

r = redis.Redis(host='127.0.0.1', port=6379, db=0, password="123456", decode_responses=True)

# 创建一个管道对象,pipeline 的模式用来解决批量提交请求
pipe = r.pipeline(transaction=False)

try:
    # 链式操作
    pipe.set("name3", "zhangsan3").set("age",18).set("sex",1)
except Exception as e:
    print(e)
    # 把管道清空
    pipe.reset()
else:
    # 执行操作
    res = pipe.execute()
    print(res)  # [True, True, True]

生产环境一般redis都是集群模式,集群模式下使用pipeline的时候,在创建pipeline的对象时,需要指定 pipe =r.pipeline(transaction=False)

上下文管理pipe:

import redis

redis_db = redis.Redis(host='127.0.0.1',port=6379, db=0, password="123456", decode_responses=True)

with redis_db.pipeline(transaction=False) as pipe:
    pipe.sadd('seta', 1).sadd('seta', 2).srem('seta', 2).lpush('lista', 1).lrange('lista', 0, -1)
    result = pipe.execute()
    
print(result)  # [1, 1, 1, 1, ['1']]

以上。

大神:

https://www.cnblogs.com/zepc007/p/10404840.html

https://www.jianshu.com/p/8505ff9dce5e

https://blog.csdn.net/pushiqiang/article/details/80444633

https://www.cnblogs.com/kangoroo/p/7647052.html

posted @ 2020-03-27 12:39  洪荒少男~  阅读(265)  评论(0编辑  收藏  举报