我使用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连接?
提前致谢!
答案 0 :(得分:1)
你是我的男人:)是的,不!使用__destruct()是保存(如在java中)连接关闭的安全方法。在PHP中这工作不同。远程连接(如db,fs ...)将被关闭,因为自定义析构函数被调用。但是对于未来:保持这种状态!它是一种正确的方式,“启动”不是瓶颈,但是:)