• Python 编程之RabbitMQ、Redis


    RabbitMQ队列

    RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统。

    对于RabbitMQ来说,生产和消费不再针对内存里的一个Queue对象,而是某台服务器上的RabbitMQ Server实现的消息队列

    实现最简单的队列通信

    send端

    import pika
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #声明queue
    channel.queue_declare(queue='hello')
    
    #In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange
    channel.basic_publish(exchange='',
                          routing_key='hello',
                          body='Hello World!')
    print(" [x] Sent 'Hello World!'")
    connection.close()

    receive端

    import pika
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #You may ask why we declare the queue again ‒ we have already declared it in our previous code.
    # We could avoid that if we were sure that the queue already exists.
    # For example if send.py program was run before. But we're not yet sure which program to run first.
    # In such cases it's a good practice to repeat declaring the queue in both programs.
    channel.queue_declare(queue='hello')
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
    
    channel.basic_consume(callback,
                          queue='hello',
                          no_ack=True)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

    通过上述代码便可以实现一个简单的生产者消费者模型,但是现在的结果是:当开启多个消费者程序的时候,启动生产者发送消息,这个时候只有一个可以收到,并且再次启动,会下一个消费者收到,类似一个轮询的关系。 

    远程连接rabbitmq server的话,需要配置权限:

    首先在rabbitmq server上创建一个用户

    rabbitmqctl add_user rbuser rbuser

    同时还要配置权限,允许从外面访问

    rabbitmqctl set_permissions -p / rbuser ".*" ".*" ".*"

    set_permissions [-p vhost] {user} {conf} {write} {read}

    vhost

    The name of the virtual host to which to grant the user access, defaulting to /.

    user

    The name of the user to grant access to the specified virtual host.

    conf

    A regular expression matching resource names for which the user is granted configure permissions.

    write

    A regular expression matching resource names for which the user is granted write permissions.

    read

    A regular expression matching resource names for which the user is granted read permissions.

    客户端连接的时候需要配置认证参数

    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()

    acknowledgment消息不丢失(通过客户端设置实现)

    RabbitMQ支持消息确认。consumer处理完一个消息,它会将Ack发回给RabbitMQ以告知,可以将相应 message 从 RabbitMQ 的消息缓存中移除。如果Ack 未被 consumer 发回给 RabbitMQ 前出现了异常,RabbitMQ 发现与该 consumer 对应的连接被断开,之后将该 message 以轮询方式发送给其他 consumer (假设存在多个 consumer 订阅同一个 queue)。

    import pika
    import time
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #You may ask why we declare the queue again ‒ we have already declared it in our previous code.
    # We could avoid that if we were sure that the queue already exists.
    # For example if send.py program was run before. But we're not yet sure which program to run first.
    # In such cases it's a good practice to repeat declaring the queue in both programs.
    channel.queue_declare(queue='hello')
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
        time.sleep(10)
        print(" [x] Done")
    
    channel.basic_consume(callback,
                          queue='hello',
                          no_ack=False)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

    如上这种方式只能实现客户端断开重新连接的时候数据不丢失,如果是rabbitmq挂了的情况如何解决?

    durable消息不丢失(通过在服务端设置保证数据不丢失)

    这个时候生产者和消费者的代码都需要改动

    send端

    import pika
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #声明queue
    channel.queue_declare(queue='task_queue',durable=True)  #make queue persistent
    
    #In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange
    channel.basic_publish(exchange='',
                          routing_key="task_queue",
                          body='Hello World!',
                          properties=pika.BasicProperties(
                             delivery_mode = 2, # make message persistent
                          ))
    
    print(" [x] Sent 'Hello World!'")
    connection.close()

    receive端

    import pika
    import time
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #You may ask why we declare the queue again ‒ we have already declared it in our previous code.
    # We could avoid that if we were sure that the queue already exists.
    # For example if send.py program was run before. But we're not yet sure which program to run first.
    # In such cases it's a good practice to repeat declaring the queue in both programs.
    channel.queue_declare(queue='task_queue',durable=True)
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
        time.sleep(10)
        print(" [x] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)
    
    channel.basic_consume(callback,
                          queue='task_queue',
                          no_ack=False)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

     这样即使在接收者接收数据过程中rabbitmq服务器出现问题了,在服务恢复之后,依然可以收到数据

    消息公平分发

    如果Rabbit只管按顺序把消息发到各个消费者身上,不考虑消费者负载的话,很可能出现,一个机器配置不高的消费者那里堆积了很多消息处理不完,同时配置高的消费者却一直很轻松。为解决此问题,可以在各个消费者端,配置perfetch=1,意思就是告诉RabbitMQ在我这个消费者当前消息还没处理完的时候就不要再给我发新消息了。

    channel.basic_qos(prefetch_count=1)

    带消息持久化+公平分发的完整代码

    import pika
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #声明queue
    channel.queue_declare(queue='task_queue',durable=True)  #make queue persistent
    
    #In RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exchange
    channel.basic_publish(exchange='',
                          routing_key="task_queue",
                          body='Hello World!',
                          properties=pika.BasicProperties(
                             delivery_mode = 2, # make message persistent
                          ))
    
    print(" [x] Sent 'Hello World!'")
    connection.close()
    生产者端
    import pika
    import time
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    #You may ask why we declare the queue again ‒ we have already declared it in our previous code.
    # We could avoid that if we were sure that the queue already exists.
    # For example if send.py program was run before. But we're not yet sure which program to run first.
    # In such cases it's a good practice to repeat declaring the queue in both programs.
    channel.queue_declare(queue='task_queue',durable=True)
    
    def callback(ch, method, properties, body):
        print(" [x] Received %r" % body)
        time.sleep(10)
        print(" [x] Done")
        ch.basic_ack(delivery_tag=method.delivery_tag)
    
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(callback,
                          queue='task_queue',
                          no_ack=False)
    
    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()
    消费者端

    消息发布订阅

    之前的例子都基本都是1对1的消息发送和接收,即消息只能发送到指定的queue里,但有些时候你想让你的消息被所有的Queue收到,类似广播的效果,这时候就要用到exchange了,

    通过exchange type = fanout参数实现,该参数表示 所有bind到此exchange的queue都可以接收消息

    发布者

    import pika
    import sys
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs',
                             exchange_type='fanout')
    
    message = ' '.join(sys.argv[1:]) or "info: Hello World!"
    channel.basic_publish(exchange='logs',
                          routing_key='',
                          body=message)
    
    print(" [x] Sent %r" % message)
    connection.close()

    订阅者

    import pika
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='logs',
                             exchange_type='fanout')
    
    #随机生成队列名字
    result = channel.queue_declare(exclusive=True)  #不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
    queue_name = result.method.queue
    
    #将exchange和队列绑定
    channel.queue_bind(exchange='logs',
                       queue=queue_name)
    
    print(' [*] Waiting for logs. To exit press CTRL+C')
    
    def callback(ch, method, properties, body):
        print(" [x] %r" % body)
    
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    
    channel.start_consuming()

    有选择的接收消息(exchange type=direct)

    RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。

    通过参数:exchange type = direct实现,该参数表示 通过routingKey和exchange决定的那个唯一的queue可以接收消息。

    生产者:

    import pika
    import sys
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='direct_logs',
                             exchange_type='direct')
    
    severity = sys.argv[1] if len(sys.argv) > 1 else 'info'
    message = ' '.join(sys.argv[2:]) or 'Hello World!'
    channel.basic_publish(exchange='direct_logs',
                          routing_key=severity,
                          body=message)
    print(" [x] Sent %r:%r" % (severity, message))
    connection.close()

    消费者:

    import pika
    import sys
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='direct_logs',
                             exchange_type='direct')
    
    #随机生成队列名字
    result = channel.queue_declare(exclusive=True)  #不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
    queue_name = result.method.queue
    
    severities = sys.argv[1:]
    if not severities:
        sys.stderr.write("Usage: %s [info] [warning] [error]
    " % sys.argv[0])
        sys.exit(1)
    
    #将exchange和队列绑定
    for severity in severities:
        channel.queue_bind(exchange='direct_logs',
                           queue=queue_name,
                           routing_key=severity)
    
    print(' [*] Waiting for logs. To exit press CTRL+C')
    
    
    def callback(ch, method, properties, body):
        print(" [x] %r:%r" % (method.routing_key, body))
    
    
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    
    channel.start_consuming()

    更细致的消息过滤

    Although using the direct exchange improved our system, it still has limitations - it can't do routing based on multiple criteria.

    In our logging system we might want to subscribe to not only logs based on severity, but also based on the source which emitted the log. You might know this concept from the syslog unix tool, which routes logs based on both severity (info/warn/crit...) and facility (auth/cron/kern...).

    That would give us a lot of flexibility - we may want to listen to just critical errors coming from 'cron' but also all logs from 'kern'.

    通过参数exchange type = topic实现,该参数表示所有符合routingKey(此时可以是一个表达式)的routingKey所bind的queue可以接收消息

      表达式符号说明:#代表一个或多个字符,*代表任何字符

      例:#.a会匹配a.a,aa.a,aaa.a,c.b.a等
              *.a会匹配a.a,b.a,c.a等

      注:使用RoutingKey为#,Exchange Type为topic的时候相当于使用fanout

    生产者:

    import pika
    import sys
    
    #连接远程rabbitmq服务器
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='topic_logs',
                             exchange_type='topic')
    
    routing_key = sys.argv[1] if len(sys.argv) > 2 else 'anonymous.info'
    message = ' '.join(sys.argv[2:]) or 'Hello World!'
    channel.basic_publish(exchange='topic_logs',
                          routing_key=routing_key,
                          body=message)
    print(" [x] Sent %r:%r" % (routing_key, message))
    connection.close()

    消费者:

    import pika
    import sys
    
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    channel = connection.channel()
    
    channel.exchange_declare(exchange='topic_logs',
                             exchange_type='topic')
    
    #随机生成队列名字
    result = channel.queue_declare(exclusive=True)  #不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除
    queue_name = result.method.queue
    
    binding_keys = sys.argv[1:]
    if not binding_keys:
        sys.stderr.write("Usage: %s [binding_key]...
    " % sys.argv[0])
        sys.exit(1)
    
    #将exchange和队列绑定
    for binding_key in binding_keys:
        channel.queue_bind(exchange='topic_logs',
                           queue=queue_name,
                           routing_key=binding_key)
    
    print(' [*] Waiting for logs. To exit press CTRL+C')
    
    def callback(ch, method, properties, body):
        print(" [x] %r:%r" % (method.routing_key, body))
    
    channel.basic_consume(callback,
                          queue=queue_name,
                          no_ack=True)
    
    channel.start_consuming()

    RabbitMQ RPC模型

    RPC(remote procedure call)模型说通俗一点就是客户端发一个请求给远程服务端,让它去执行,然后服务端端再把执行的结果再返回给客户端。

    server端

    import pika
    
    # 远程连接RabbitMQ
    credentials = pika.PlainCredentials('rbuser', 'rbuser')
    connection = pika.BlockingConnection(pika.ConnectionParameters(
        '192.168.189.136',5672,'/',credentials
    ))
    
    # 声明管道
    channel = connection.channel()
    
    # 声明queue
    channel.queue_declare(queue='rpc_queue')
    
    def fib(n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return fib(n-1) + fib(n-2)
    
    def on_request(ch, method, props, body):    # props 是客户端发过来的消息
        n = int(body)
    
        print(" [.] fib(%s)" % n)
        response = fib(n)
        # 服务端发布消息
        ch.basic_publish(exchange='',
                         routing_key=props.reply_to,    # props.reply_to从客户端取出双方约定好存放返回结果的queue
                         properties=pika.BasicProperties(correlation_id = 
                                                             props.correlation_id),     # props.correlation_id 从客户端取出当前请求的ID返回给客户端做验证
                         body=str(response))
        ch.basic_ack(delivery_tag = method.delivery_tag)    # 手动确认消息被消费
    
    channel.basic_qos(prefetch_count=1)     # 每次最多处理一个客户端发过来的消息
    # 服务端消费消息
    channel.basic_consume(on_request,   # 服务端一收到消息就执行 on_request回调函数
                          queue='rpc_queue')
    
    print(" [x] Awaiting RPC requests")
    channel.start_consuming()

    client端

    import pika
    import uuid
    import time
    
    class FibonacciRpcClient(object):
        def __init__(self):
            # 远程连接RabbitMQ
            credentials = pika.PlainCredentials('rbuser', 'rbuser')
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(
                '192.168.189.136', 5672, '/', credentials
            ))
    
            # 声明管道
            self.channel = self.connection.channel()
    
            # 创建随机队列,用来接收服务器端返回的消息
            result = self.channel.queue_declare(exclusive=True)
            self.callback_queue = result.method.queue
    
            # 客户端消费消息
            self.channel.basic_consume(self.on_response, no_ack=True,   # 客户端一收到消息就执行on_response回调函数
                                       queue=self.callback_queue)
    
        def on_response(self, ch, method, props, body):
            print("---->", method, props)
            # 当服务端返回的id跟当初请求的id一致时,再去读取服务端发送的信息保持数据的一致性
            if self.corr_id == props.correlation_id:
                self.response = body
    
        def call(self, n):
            self.response = None
            self.corr_id = str(uuid.uuid4())
            # 客户端发布消息
            self.channel.basic_publish(exchange='',
                                       routing_key='rpc_queue',     # 客户端把请求发送到这个queue
                                       properties=pika.BasicProperties(     # 定义基本属性
                                             reply_to = self.callback_queue,    # 定义客户端服务端双方response的所用的queue
                                             correlation_id = self.corr_id,     # 定义这次request的唯一ID
                                             ),
                                       body=str(n))
            while self.response is None:
                self.connection.process_data_events()   # 相当于 非阻塞版的start_consumer()
                print("no msg ...")
                time.sleep(0.5)
            return int(self.response)
    
    fibonacci_rpc = FibonacciRpcClient()
    
    print(" [x] Requesting fib(30)")
    response = fibonacci_rpc.call(30)
    print(" [.] Got %r" % response)

    redis缓存

    redis是业界主流的key-value nosql 数据库之一。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

    Redis优点

    • 异常快速 : Redis是非常快的,每秒可以执行大约110000设置操作,81000个/每秒的读取操作。

    • 支持丰富的数据类型 : Redis支持最大多数开发人员已经知道如列表,集合,可排序集合,哈希等数据类型。

      这使得在应用中很容易解决的各种问题,因为我们知道哪些问题处理使用哪种数据类型更好解决。
    • 操作都是原子的 : 所有 Redis 的操作都是原子,从而确保当两个客户同时访问 Redis 服务器得到的是更新后的值(最新值)。

    • MultiUtility工具:Redis是一个多功能实用工具,可以在很多如:缓存,消息传递队列中使用(Redis原生支持发布/订阅),在应用程序中,如:Web应用程序会话,网站页面点击数等任何短暂的数据;

    Redis 连接方式

    1. 操作模式

    redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令,Redis是StrictRedis的子类,用于向后兼容旧版本的redis-py。

    >>> import redis
    >>> r = redis.Redis(host='192.168.189.136', port=6379)
    >>> r.set('foo', 'Bar')
    True
    >>> print(r.get('foo'))
    b'Bar'

    2. 连接池

    redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。

    操作

    1. String操作

    redis中的String在在内存中按照一个name对应一个value来存储。如图:

    set(name, value, ex=None, px=None, nx=False, xx=False)

    在Redis中设置值,默认,不存在则创建,存在则修改
    参数:
         ex,过期时间(秒),过期后自动删除该name
         px,过期时间(毫秒),过期后自动删除该name
         nx,如果设置为True,则只有name不存在时,当前set操作才执行
         xx,如果设置为True,则只有name存在时,岗前set操作才执行

    setnx(name, value)

    设置值,只有name不存在时,执行设置操作(添加)

    setex(name, value, time)

    # 设置值
    # 参数:
        # time,过期时间(数字秒 或 timedelta对象)

    psetex(name, time_ms, value)

    # 设置值
    # 参数:
        # time_ms,过期时间(数字毫秒 或 timedelta对象)

    mset(*args, **kwargs)

    批量设置值
    如:
        mset(k1='v1', k2='v2')
        或
        mset({'k1': 'v1', 'k2': 'v2'})

    get(name)

    获取值

    mget(keys, *args)

    批量获取
    如:
        mget('k1', 'k2')
        或
        mget(['x1', 'x2'])

    getset(name, value)

    设置新值并获取原来的值

    getrange(key, start, end)

    # 获取子序列(根据字节获取,非字符)
    # 参数:
        # key,Redis 的 key
        # start,起始位置(字节)
        # end,结束位置(字节)
    # 如: name="张三" ,0-2表示 "张"
        r.getrange('name',0,2)

    setrange(name, offset, value)

    # 修改字符串内容,从指定字符串索引开始向后替换(新值太长时,则向后添加)
    # 参数:
        # offset,字符串的索引,字节(一个汉字三个字节)
        # value,要设置的值

    setbit(name, offset, value)

    # 对name对应值的二进制表示的位进行操作
     
    # 参数:
        # name,redis的name
        # offset,位的索引(将值变换成二进制后再进行索引)
        # value,值只能是 1 或 0
     
    # 注:如果在Redis中有一个对应: n1 = "foo",
            那么字符串foo的二进制表示为:01100110 01101111 01101111
        所以,如果执行 setbit('n1', 7, 1),则就会将第7位设置为1,
            那么最终二进制则变成 01100111 01101111 01101111,即:"goo"
     
    # 扩展,转换二进制表示:
     
        # source = "武沛齐"
        source = "foo"
     
        for i in source:
            num = ord(i)
            print bin(num).replace('b','')
     
        特别的,如果source是汉字 "武沛齐"怎么办?
        答:对于utf-8,每一个汉字占 3 个字节,那么 "武沛齐" 则有 9个字节
           对于汉字,for循环时候会按照 字节 迭代,那么在迭代时,将每一个字节转换 十进制数,然后再将十进制数转换成二进制
            11100110 10101101 10100110 11100110 10110010 10011011 11101001 10111101 10010000
            -------------------------- ----------------------------- -----------------------------
                        武                         沛                           齐

    *用途举例,用最省空间的方式,存储在线用户数及分别是哪些用户在线

    getbit(name, offset)

    # 获取name对应的值的二进制表示中的某位的值 (0或1)

    bitcount(key, start=None, end=None)

    # 获取name对应的值的二进制表示中 1 的个数
    # 参数:
        # key,Redis的name
        # start,位起始位置
        # end,位结束位置

    strlen(name)

    # 返回name对应值的字节长度(一个汉字3个字节)

    incr(self, name, amount=1)

    # 自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。
     
    # 参数:
        # name,Redis的name
        # amount,自增数(必须是整数)
     
    # 注:同incrby

    incrbyfloat(self, name, amount=1.0)

    # 自增 name对应的值,当name不存在时,则创建name=amount,否则,则自增。
     
    # 参数:
        # name,Redis的name
        # amount,自增数(浮点型)

    decr(self, name, amount=1)

    # 自减 name对应的值,当name不存在时,则创建name=amount,否则,则自减。
     
    # 参数:
        # name,Redis的name
        # amount,自减数(整数)

    append(key, value)

    # 在redis name对应的值后面追加内容
     
    # 参数:
        key, redis的name
        value, 要追加的字符串

    2. Hash操作

    hash表现形式上有些像pyhton中的dict,可以存储一组关联性较强的数据 , redis中Hash在内存中的存储格式如下图:

    hset(name, key, value)

    # name对应的hash中设置一个键值对(不存在,则创建;否则,修改)
     
    # 参数:
        # name,redis的name
        # key,name对应的hash中的key
        # value,name对应的hash中的value
     
    # 注:
        # hsetnx(name, key, value),当name对应的hash中不存在当前key时则创建(相当于添加)

    hmset(name, mapping)

    # 在name对应的hash中批量设置键值对
     
    # 参数:
        # name,redis的name
        # mapping,字典,如:{'k1':'v1', 'k2': 'v2'}
     
    # 如:
        # r.hmset('xx', {'k1':'v1', 'k2': 'v2'})

    hget(name,key)

    # 在name对应的hash中获取根据key获取value

    hmget(name, keys, *args)

    # 在name对应的hash中获取多个key的值
     
    # 参数:
        # name,reids对应的name
        # keys,要获取key集合,如:['k1', 'k2', 'k3']
        # *args,要获取的key,如:k1,k2,k3
     
    # 如:
        # r.hmget('xx', ['k1', 'k2'])
        #
        # r.hmget('xx', 'k1', 'k2')

    hgetall(name)

    获取name对应hash的所有键值

    hlen(name)

    # 获取name对应的hash中键值对的个数

    hkeys(name)

    # 获取name对应的hash中所有的key的值

    hvals(name)

    # 获取name对应的hash中所有的value的值

    hexists(name, key)

    # 检查name对应的hash是否存在当前传入的key

    hdel(name,*keys)

    # 将name对应的hash中指定key的键值对删除

    hincrby(name, key, amount=1)

    # 自增name对应的hash中的指定key的值,不存在则创建key=amount
    # 参数:
        # name,redis中的name
        # key, hash对应的key
        # amount,自增数(整数)

    hincrby(name, key, amount=1)

    # 自增name对应的hash中的指定key的值,不存在则创建key=amount
    # 参数:
        # name,redis中的name
        # key, hash对应的key
        # amount,自增数(整数)

    hincrbyfloat(name, key, amount=1.0)

    # 自增name对应的hash中的指定key的值,不存在则创建key=amount
     
    # 参数:
        # name,redis中的name
        # key, hash对应的key
        # amount,自增数(浮点数)
     
    # 自增name对应的hash中的指定key的值,不存在则创建key=amount

    hscan(name, cursor=0, match=None, count=None)

    Start a full hash scan with:

    HSCAN myhash 0

    Start a hash scan with fields matching a pattern with:

    HSCAN myhash 0 MATCH order_*

    Start a hash scan with fields matching a pattern and forcing the scan command to do more scanning with:

    HSCAN myhash 0 MATCH order_* COUNT 1000

    # 增量式迭代获取,对于数据大的数据非常有用,hscan可以实现分片的获取数据,并非一次性将数据全部获取完,从而放置内存被撑爆
     
    # 参数:
        # name,redis的name
        # cursor,游标(基于游标分批取获取数据)
        # match,匹配指定key,默认None 表示所有的key
        # count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
     
    # 如:
        # 第一次:cursor1, data1 = r.hscan('xx', cursor=0, match=None, count=None)
        # 第二次:cursor2, data1 = r.hscan('xx', cursor=cursor1, match=None, count=None)
        # ...
        # 直到返回值cursor的值为0时,表示数据已经通过分片获取完毕

    hscan_iter(name, match=None, count=None)

    # 利用yield封装hscan创建生成器,实现分批去redis中获取数据
      
    # 参数:
        # match,匹配指定key,默认None 表示所有的key
        # count,每次分片最少获取个数,默认None表示采用Redis的默认分片个数
      
    # 如:
        # for item in r.hscan_iter('xx'):
        #     print item

    3. list操作

    List操作,redis中的List在在内存中按照一个name对应一个List来存储。如图:

    lpush(name,values)

    # 在name对应的list中添加元素,每个新的元素都添加到列表的最左边
     
    # 如:
        # r.lpush('oo', 11,22,33)
        # 保存顺序为: 33,22,11
     
    # 扩展:
        # rpush(name, values) 表示从右向左操作

    lpushx(name,value)

    # 在name对应的list中添加元素,只有name已经存在时,值添加到列表的最左边
     
    # 更多:
        # rpushx(name, value) 表示从右向左操作

    llen(name)

    # name对应的list元素的个数

    linsert(name, where, refvalue, value))

    # 在name对应的列表的某一个值前或后插入一个新值
     
    # 参数:
        # name,redis的name
        # where,BEFORE或AFTER
        # refvalue,标杆值,即:在它前后插入数据
        # value,要插入的数据
    # 如:
    >>> r.rpush('mylist','Hello')
    1
    >>> r.rpush('mylist','World')
    2
    >>> r.linsert('mylist','BEFORE','World','There')
    3
    >>> r.lrange('mylist',0,-1)
    [b'Hello', b'There', b'World']

    r.lset(name, index, value)

    # 对name对应的list中的某一个索引位置重新赋值
     
    # 参数:
        # name,redis的name
        # index,list的索引位置
        # value,要设置的值
    # 如:
    >>> r.lset('mylist',0,'xx')
    True
    >>> r.lrange('mylist',0,-1)
    [b'xx', b'There', b'World']

    r.lrem(name, value, num=0)

    # 在name对应的list中删除指定的值
     
    # 参数:
        # name,redis的name
        # value,要删除的值
        # num,  num=0,删除列表中所有与 VALUE 相等的值;
               # num=2,从前到后搜索,删除2个与VALUE 相等的值;
               # num=-2,从后向前搜索,删除2个与VALUE 相等的值
    # 如:
    >>> r.lrange('mylist',0,-1)
    [b'xx', b'There', b'World', b'xx', b'xx']
    >>> r.lrem('mylist','xx',2)
    2
    >>> r.lrange('mylist',0,-1)
    [b'There', b'World', b'xx']

    lpop(name)

    # 在name对应的列表的左侧获取第一个元素并在列表中移除,返回值则是第一个元素
     
    # 更多:
        # rpop(name) 表示从右向左操作

    lindex(name, index)

    # 在name对应的列表中根据索引获取列表元素

    lrange(name, start, end)

    # 在name对应的列表分片获取数据
    # 参数:
        # name,redis的name
        # start,索引的起始位置
        # end,索引结束位置
    # 如:
    r.lrange('mylist',0,-1)    #表示获取全部元素

    ltrim(name, start, end)

    # 在name对应的列表中移除没有在start-end索引之间的值
    # 参数:
        # name,redis的name
        # start,索引的起始位置
        # end,索引结束位置

    rpoplpush(src, dst)

    # 从一个列表取出最右边的元素,同时将其添加至另一个列表的最左边
    # 参数:
        # src,要取数据的列表的name
        # dst,要添加数据的列表的name

    blpop(keys, timeout)

    # 将多个列表排列,按照从左到右去pop对应列表的元素
     
    # 参数:
        # keys,redis的name的集合
        # timeout,超时时间,当元素所有列表的元素获取完之后,阻塞等待列表内有数据的时间(秒), 0 表示永远阻塞
     
    # 更多:
        # r.brpop(keys, timeout),从右向左获取数据
    
    如:
    >>> r.lrange('mylist',0,-1)
    [b'tom', b'lily', b'lucy']
    >>> r.blpop('mylist')
    (b'mylist', b'tom')
    >>> r.blpop('mylist')
    (b'mylist', b'lily')
    >>> r.blpop('mylist')
    (b'mylist', b'lucy')
    >>> r.lrange('mylist',0,-1)
    []
    >>> r.blpop('mylist',5)    #列表为空,则等待5秒返回结果

    brpoplpush(src, dst, timeout=0)

    # 从一个列表的右侧移除一个元素并将其添加到另一个列表的左侧
     
    # 参数:
        # src,取出并要移除元素的列表对应的name
        # dst,要插入元素的列表对应的name
        # timeout,当src对应的列表中没有数据时,阻塞等待其有数据的超时时间(秒),0 表示永远阻塞

    4. Set集合操作

    Set集合就是不允许重复的列表

    sadd(name,values)

    # name对应的集合中添加元素

    scard(name)

    # 获取name对应的集合中元素个数

    sdiff(keys, *args)

    # 在第一个name对应的集合中且不在其他name对应的集合的元素集合(差集)
    # 如:
    >>> r.smembers('key1')
    {b'a', b'b', b'c'}
    >>> r.smembers('key2')
    {b'c', b'b', b'e', b'd'}
    >>> r.sdiff('key1','key2')
    {b'a'}

    sdiffstore(dest, keys, *args)

    # 获取第一个name对应的集合中且不在其他name对应的集合,再将其存储到dest对应的集合中,如果dest集合已存在,则会被覆盖
    # 如:
    >>> r.smembers('key1')
    {b'a', b'b', b'c'}
    >>> r.smembers('key2')
    {b'c', b'b', b'e', b'd'}
    >>> r.smembers('key3')
    {b'e', b'd'}
    >>> r.sdiff('key1','key2')
    {b'a'}
    >>> r.sdiffstore('key3','key1','key2')
    1
    >>> r.smembers('key3')
    {b'a'}

    sinter(keys, *args)

    # 返回在第一个name对应的集合中且在其他name对应的集合的元素集合(交集)
    如:
    >>> r.smembers('key1')
    {b'a', b'b', b'c'}
    >>> r.smembers('key2')
    {b'c', b'b', b'e', b'd'}
    >>> r.sinter('key1','key2')
    {b'b', b'c'}

    sinterstore(dest, keys, *args)

    # 获取第一个name对应的集合中且在其他name对应的集合,再将其存储到dest对应的集合中,如果dest集合已存在,则会被覆盖
    如:
    >>> r.smembers('key1')
    {b'a', b'b', b'c'}
    >>> r.smembers('key2')
    {b'c', b'b', b'e', b'd'}
    >>> r.smembers('key3')
    {b'a'}
    >>> r.sinterstore('key3','key1','key2')
    2
    >>> r.smembers('key3')
    {b'b', b'c'}

    sismember(name, value)

    # 检查value是否是name对应的集合的成员
    如:
    >>> r.smembers('key1')
    {b'a', b'b', b'c'}
    >>> r.sismember('key1','b')
    True
    >>> r.sismember('key1','e')
    False

    smembers(name)

    # 获取name对应的集合的所有成员

    smove(src, dst, value)

    # 将某个成员从一个集合中移动到另外一个集合

    spop(name)

    # 从集合的右侧(尾部)移除一个成员,并将其返回

    srandmember(name, numbers)

    # 从name对应的集合中随机获取 numbers 个元素

    srem(name, values)

    # 在name对应的集合中删除一个或多个指定值

    sunion(keys, *args)

    # 返回给定集合的并集。不存在的集合 key 被视为空集。

    sunionstore(dest,keys, *args)

    # 获取给定集合的并集,并将其存储到dest对应的集合中,如果dest集合已存在,则会被覆盖

    sscan(name, cursor=0, match=None, count=None)
    sscan_iter(name, match=None, count=None)

    # 同字符串的操作,用于增量迭代分批获取元素,避免内存消耗太大

    有序集合,在集合的基础上,为每元素排序;元素的排序需要根据另外一个值来进行比较,所以,对于有序集合,每一个元素有两个值,即:值和分数,分数专门用来做排序。

    zadd(name, *args, **kwargs)

    # 在name对应的有序集合中添加元素
    # 如:
         # zadd('zz', 'n1', 1, 'n2', 2)
         #
         # zadd('zz', n1=1, n2=2)

    zcard(name)

    # 获取name对应的有序集合元素的数量

    zcount(name, min, max)

    # 获取name对应的有序集合中分数 在 [min,max] 之间的个数
    如:
    >>> r.zadd('zz',n1=1,n2=2,n3=3,n4=4,n5=5,n6=10,n7=15)
    1
    >>> r.zcount('zz',2,14)
    5

    zincrby(name, value, amount)

    # 自增name对应的有序集合的 name 对应的分数

    r.zrange( name, start, end, desc=False, withscores=False, score_cast_func=float)

    # 按照索引范围获取name对应的有序集合的元素
     
    # 参数:
        # name,redis的name
        # start,有序集合索引起始位置(非分数)
        # end,有序集合索引结束位置(非分数)
        # desc,排序规则,默认按照分数从小到大排序
        # withscores,是否获取元素的分数,默认只获取元素的值
        # score_cast_func,对分数进行数据转换的函数
     
    # 更多:
        # 从大到小排序
        # zrevrange(name, start, end, withscores=False, score_cast_func=float)
     
        # 按照分数范围获取name对应的有序集合的元素
        # zrangebyscore(name, min, max, start=None, num=None, withscores=False, score_cast_func=float)
        # 从大到小排序
        # zrevrangebyscore(name, max, min, start=None, num=None, withscores=False, score_cast_func=float)

    zrank(name, value)

    # 获取某个值在 name对应的有序集合中的排名(从 0 开始)
     
    # 更多:
        # zrevrank(name, value),从大到小排序

    zrem(name, values)

    # 删除name对应的有序集合中值是values的成员
     
    # 如:zrem('zz', 's1', 's2')

    zremrangebyrank(name, min, max)

    # 根据排行范围删除

    zremrangebyscore(name, min, max)

    # 根据分数范围删除

    zscore(name, value)

    # 获取name对应有序集合中 value 对应的分数

    zinterstore(dest, keys, aggregate=None)

    # 获取两个有序集合的交集,如果遇到相同值,则按照aggregate进行操作
    # aggregate的值为:  SUM  MIN  MAX

    zunionstore(dest, keys, aggregate=None)

    # 获取两个有序集合的并集,如果遇到相同值不同分数,则按照aggregate进行操作
    # aggregate的值为:  SUM  MIN  MAX

    zscan(name, cursor=0, match=None, count=None, score_cast_func=float)
    zscan_iter(name, match=None, count=None,score_cast_func=float)

    # 同字符串相似,相较于字符串新增score_cast_func,用来对分数进行操作

    其他常用操作

    delete(*names)

    # 根据删除redis中的任意数据类型

    exists(name)

    # 检测redis的name是否存在

    keys(pattern='*')

    # 根据模型获取redis的name
     
    # 更多:
        # KEYS * 匹配数据库中所有 key 。
        # KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
        # KEYS h*llo 匹配 hllo 和 heeeeello 等。
        # KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo

    expire(name ,time)

    # 为某个redis的某个name设置超时时间

    rename(src, dst)

    # 对redis的name重命名为

    move(name, db))

    # 将redis的某个值移动到指定的db下

    randomkey()

    # 随机获取一个redis的name(不删除)

    type(name)

    # 获取name对应值的类型

    scan(cursor=0, match=None, count=None)
    scan_iter(match=None, count=None)

    # 同字符串操作,用于增量迭代获取key

    管道

    redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。

    import redis
     
    pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
     
    r = redis.Redis(connection_pool=pool)
     
    # pipe = r.pipeline(transaction=False)
    pipe = r.pipeline(transaction=True)
     
    pipe.set('name', 'alex')
    pipe.set('role', 'sb')
     
    pipe.execute()
  • 相关阅读:
    月经贴——.net前景何妨!
    [Asp.net 5] Options-配置文件之后的配置
    [Asp.net 5] DependencyInjection项目代码分析4-微软的实现(5)(IEnumerable<>补充)
    [Asp.net 5] Logging-其他日志系统的实现
    [Asp.net 5] Logging-日志系统的基本架构(下)
    [Asp.net 5] Logging-日志系统的基本架构(上)
    [Asp.net 5] Logging-新日志系统目录
    [Asp.net 5] Localization-简单易用的本地化
    [Asp.net 5] Localization-Asp.net运行时多语言
    java-多线程安全问题
  • 原文地址:https://www.cnblogs.com/cyfiy/p/9287980.html
Copyright © 2020-2023  润新知