簡體   English   中英

python中的Redis,如何關閉連接?

[英]Redis in python, how do you close the connection?

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

我知道在 ruby​​ 中我們使用了 quit() 方法。 我在這里找不到任何關於 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

紅寶石

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

只需使用redis.Redis 它在后台使用連接池,因此您不必擔心在該級別進行管理。

如果您絕對必須使用低級連接,則需要執行通常由redis.Redis為您完成的響應處理。

以下是使用低級連接執行單個命令的示例:

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

用法示例:

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

但正如我之前所說,在 99.9% 的情況下, redis.Redisredis.Redis的方法。

StrictRedis 本身不實現連接語義,而是使用連接池,該池可用作 StrictRedis 實例的屬性: S.connection_pool connection_pool 對象有一個disconnect方法,可以在必要時強制立即斷開池中的所有連接,但是當您的 StrictRedis 對象超出范圍時,池中的各個連接都會在沒有您干預的情況下自行清理(請參閱 redis/connection.json )。 py:392-396)

使用Redis連接池。 您不需要明確關閉它。

import redis

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

並且可以提高效率。

使用ConnectionPool時無需擔心。查看源代碼:

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)

最后,無論您做什么,每個連接都會釋放到池中,並將分配給其他客戶端。

@shangliuyan我閱讀了pool.release()源代碼,發現以下代碼: 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)

以及_checkpid方法,如下所示: 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()我的問題是,當self.pid等於os.getpid或進程被殺死時,如何自動關閉連接?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM