我正在使用 phpredis 连接到 Redis 服务器 ( https://github.com/phpredis/phpredis )。我为我的应用程序编写了一个非常基本的 Redis 客户端,它应该简单地采用 env 参数并连接到 Redis 服务器。我的 Redis 客户端如下所示:
<?php
use \Redis
class Redis
{
/** @var Redis */
private $redis;
/**
* @param RedisServer $redis
* @param string $redisHost
* @param string $redisPort
*/
public function __construct(RedisServer $redis, string $redisHost, string $redisPort)
{
$this->redis = $redis;
if (!$this->redis->connect($redisHost, $redisPort)) {
throw new ConnectionException('Failed to connection to redis server', 500);
}
}
/**
* Close connection when Redis service is destroyed
*/
public function __destruct()
{
$this->redis->close();
$this->redis = null;
}
//....
}
我需要在 __destruct() 中显式关闭 Redis 连接吗?
提前致谢!
最佳答案
你是我的男人:) 是的,也不是!使用 __destruct() 是保存(就像在 java 中)关闭连接的安全方法。在 php 中,这工作有所不同。远程连接(如 db、fs...)将在调用自定义析构函数之前关闭。但为了 future :继续努力!这是一个正确的方法,“启动”还不是瓶颈:)
关于PHP 连接到 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428924/