Redis in python, how do you close the connection?

Posted ExplorerMan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Redis in python, how do you close the connection?相关的知识,希望对你有一定的参考价值。

 

down voteaccepted

Just use redis.Redis. It uses a connection pool under the hood, so you don‘t have to worry about managing at that level.

If you absolutely have to use a low level connection, you need to do the response handling that is normally done for you by redis.Redis.

Here‘s an example of executing a single command using the low level connection:

def execute_low_level(command, *args, **kwargs):
    connection = redis.Connection(**kwargs)
    try:
        connection.connect()
        connection.send_command(command, *args)

        response = connection.read_response()
        if command in redis.Redis.RESPONSE_CALLBACKS:
            return redis.Redis.RESPONSE_CALLBACKS[command](response)
        return response

    finally:
        del connection

Example usage:

response = execute_low_level(
        ‘HGET‘, ‘redis:key‘, ‘hash:key‘, host=‘localhost‘, port=6379)

But as I said before, redis.Redis is the way to go in 99.9% of cases.

 

 

 

you dont need worry about it when you use ConnectionPool.look at the source code:

def execute_command(self, *args, **options):
    "Execute a command and return a parsed response"
    pool = self.connection_pool
    command_name = args[0]
    connection = pool.get_connection(command_name, **options)
    try: 
        connection.send_command(*args)
        return self.parse_response(connection, command_name, **options)
    except (ConnectionError, TimeoutError) as e:
        connection.disconnect()
        if not connection.retry_on_timeout and isinstance(e, TimeoutError):
            raise
        connection.send_command(*args)
        return self.parse_response(connection, command_name, **options)
    finally:
        pool.release(connection)

finally,every connection will release to the pool no matter what you do, and it will assign to other client.

以上是关于Redis in python, how do you close the connection?的主要内容,如果未能解决你的问题,请参考以下文章

python http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in

How do I duplicate a resource reference in code behind in WPF?

[转]How do I use variables in Oracle SQL Developer?

How do I UPDATE from a SELECT in SQL Server?

How Do We Debug in Embedded System

How do I create a List in Scala?