Skip to content

Commit

Permalink
修复 Redis 连接上下文 delayDestroy 没有真正删除数据 (#475)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yurunsoft committed Mar 3, 2023
1 parent 32e54c6 commit 9d9b07f
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/Server/ConnectionContext/StoreHandler/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ class Redis implements IHandler
*/
private int $masterPID = 0;

/**
* 销毁数据的定时器ID.
*/
private ?int $destroyTimerId = null;

/**
* 要销毁的键名数组.
*/
private array $destroyKeys = [];

public function __init(): void
{
if ('' === $this->key)
Expand All @@ -90,6 +100,8 @@ public function __init(): void
$this->startPing($redis);
});
}

$this->startDestroyTimer();
}

/**
Expand Down Expand Up @@ -194,6 +206,10 @@ public function __destruct()
{
Timer::del($this->timerId);
}
if (null !== $this->destroyTimerId)
{
Timer::del($this->destroyTimerId);
}
}

/**
Expand Down Expand Up @@ -250,9 +266,7 @@ public function destroy(string $key): void
*/
public function delayDestroy(string $key, int $ttl): void
{
$this->useRedis(function (RedisHandler $redis) use ($ttl) {
$redis->expire($this->getStoreKey(), $ttl);
});
Timer::after($ttl * 1000, fn () => $this->destroyKeys[] = $key);
}

/**
Expand Down Expand Up @@ -428,4 +442,21 @@ public function getOldClientIdByFlag(string $flag): ?int
{
return $this->useRedis(fn (RedisHandler $redis) => $redis->get($this->key . ':binder:old:' . $flag) ?: null);
}

private function startDestroyTimer(): void
{
Timer::tick(1000, function () {
if ($keys = $this->destroyKeys)
{
$this->destroyKeys = [];
$storeKey = $this->getStoreKey();
$this->useRedis(static function (RedisHandler $redis) use ($keys, $storeKey) {
foreach (array_chunk($keys, 1000) as $keysChunk)
{
$redis->hDel($storeKey, ...$keysChunk);
}
});
}
});
}
}

0 comments on commit 9d9b07f

Please sign in to comment.