Skip to content

Commit ff0b1e6

Browse files
committed
Fixed redis not reconnect after redis server restarted.
1 parent 042e447 commit ff0b1e6

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

src/Pool/PoolFactory.php

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414

1515
use Hyperf\Di\Container;
1616
use Psr\Container\ContainerInterface;
17-
use Swoole\Coroutine\Channel;
1817

1918
class PoolFactory
2019
{

src/Redis.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public function __call($name, $arguments)
3939
$connection = $this->getConnection($hasContextConnection);
4040

4141
try {
42+
$connection = $connection->getConnection();
4243
// Execute the command with the arguments.
4344
$result = $connection->{$name}(...$arguments);
4445
} finally {
@@ -88,7 +89,7 @@ private function getConnection($hasContextConnection): RedisConnection
8889
}
8990
if (! $connection instanceof RedisConnection) {
9091
$pool = $this->factory->getPool($this->poolName);
91-
$connection = $pool->get()->getConnection();
92+
return $pool->get();
9293
}
9394
return $connection;
9495
}

src/RedisConnection.php

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
namespace Hyperf\Redis;
1414

1515
use Hyperf\Contract\ConnectionInterface;
16+
use Hyperf\Contract\StdoutLoggerInterface;
1617
use Hyperf\Pool\Connection as BaseConnection;
1718
use Hyperf\Pool\Exception\ConnectionException;
1819
use Hyperf\Pool\Pool;
@@ -53,7 +54,13 @@ public function __construct(ContainerInterface $container, Pool $pool, array $co
5354

5455
public function __call($name, $arguments)
5556
{
56-
return $this->connection->{$name}(...$arguments);
57+
try {
58+
$result = $this->connection->{$name}(...$arguments);
59+
} catch (\Throwable $exception) {
60+
$result = $this->retry($name, $arguments, $exception);
61+
}
62+
63+
return $result;
5764
}
5865

5966
public function getActiveConnection()
@@ -125,4 +132,20 @@ public function setDatabase(?int $database): void
125132
{
126133
$this->database = $database;
127134
}
135+
136+
protected function retry($name, $arguments, \Throwable $exception)
137+
{
138+
$logger = $this->container->get(StdoutLoggerInterface::class);
139+
$logger->warning(sprintf('Redis::__call failed, bacause ' . $exception->getMessage()));
140+
141+
try {
142+
$this->reconnect();
143+
$result = $this->connection->{$name}(...$arguments);
144+
} catch (\Throwable $exception) {
145+
$this->lastUseTime = 0.0;
146+
throw $exception;
147+
}
148+
149+
return $result;
150+
}
128151
}

0 commit comments

Comments
 (0)