• Redis连接


    Python操作Redis连接

    linux安装:https://www.redis.com.cn/linux-install-redis.html

    windows安装:https://www.redis.com.cn/redis-installation.html

    1.Redis连接

    import redis
    
    # decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
    rdb = redis.Redis(host='localhost', port=6379, db=15, password='xx', decode_response=True)
    rdb.set(name='A', value='123', ex=None, px=None, nx=False, xx=False)
    a = rdb.get('A')
    

    2. Redis连接池

    # 方式一:Redis连接池(官方不推荐)
    from redis import ConnectionPool, Redis
    
    # decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
    # max_connections=10 指定连接数
    pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_response=True, max_connections=10)
    rdb = Redis(connection_pool=pool)
    rdb.set('B', '777')
    b = rdb.get('B')
    
    # 方式二:StrictRedis连接池
    from redis import ConnectionPool, StrictRedis
    
    # decode_response=True 指定输出str类型(redis输出的数据类型为bytes)
    # max_connections=10 指定连接数
    pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_response=True, max_connections=10)
    rdb = StrictRedis(connection_pool=pool)
    rdb.set('C', '778')
    b = rdb.get('C')
    

    3.Redis管道

    redis-python 默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作

    pipeline 则支持在连接和断开之间,执行多个操作

    from redis import ConnectionPool, StrictRedis
    import time
    
    pool = ConnectionPool(host='localhost', port=6379, db=15, password='xx', decode_responses=True)
    r = redis.Redis(connection_pool=pool)
    
    # 默认的情况下,管道里执行的命令可以保证执行的原子性
    # pipe = r.pipeline(transaction=False) 可以禁用这一特性。
    # pipe = r.pipeline(transaction=True)  默认情况
    # 集群模式下使用pipeline,在创建pipeline的对象时,需指定
    # pipe =conn.pipeline(transaction=False)
    
    pipe = r.pipeline() # 创建一个管道
    
    # pipe.multi() 启动管道的事务块,可通过`execute`结束事务块
    pipe.set('name', 'jack')
    pipe.set('age', 20)
    pipe.sadd('set_name', 'a', 'b')
    pipe.execute()
    
  • 相关阅读:
    Kibana:使用 Elasticsearch 和 Kibana 进行动态数据
    pyperclip 模块
    Kibana:在 Kibana 中使用 Vega
    QT翻金币例子
    xlrd模块
    unrar模块
    Locust压测框架实战:HTTP脚本编写
    基于Android系统的自动化环境搭建
    收下这份实操案例,还怕不会用Jmeter接口测试工具?!
    这里有篇Charles详细教程,看完后就可以把Fiddler卸载
  • 原文地址:https://www.cnblogs.com/bbiu/p/14107179.html
Copyright © 2020-2023  润新知