简体   繁体   中英

Redis in python, how do you close the connection?

https://github.com/andymccurdy/redis-py

I know in ruby we use the quit() method. I can't find anything here for python

python:

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
r.set('foo', 'bar')
print r.get('foo')
#r.close() doesn't work

ruby

require "redis"
redis = Redis.new
redis.set("mykey", "hello world")
puts redis.get("mykey")
redis.quit()

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.

StrictRedis doesn't implement connection semantics itself, instead it uses a connection pool, which is available as a property of a StrictRedis instance: S.connection_pool . The connection_pool object has a disconnect method to force an immediate disconnect of all connections in the pool if necessary, however when your StrictRedis object goes out of scope, the individual connections in the pool all clean themselves up without your intervention (see redis/connection.py:392-396)

Use Redis connection pool. You don't need to explicitly close it.

import redis

pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.Redis(connection_pool=pool)

And can improve efficiency.

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.

@shangliuyan I read the pool.release() source code and I found the code as below: def release(self, connection): "Releases the connection back to the pool" self._checkpid() if connection.pid != self.pid: return self._in_use_connections.remove(connection) self._available_connections.append(connection)

and the _checkpid method as below: def _checkpid(self): if self.pid != os.getpid(): with self._check_lock: if self.pid == os.getpid(): # another thread already did the work while we waited # on the lock. return self.disconnect() self.reset() def _checkpid(self): if self.pid != os.getpid(): with self._check_lock: if self.pid == os.getpid(): # another thread already did the work while we waited # on the lock. return self.disconnect() self.reset() my question is, when the self.pid is equal to os.getpid or when the process was killed, how close the connection automatic?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM