Skip to content

Commit 88a9f5c

Browse files
committed
use swoole table
1 parent ba34945 commit 88a9f5c

File tree

1 file changed

+12
-29
lines changed

1 file changed

+12
-29
lines changed

src/TableCache.php

+12-29
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,25 @@
55
namespace Rabbit\Cache;
66

77
use Psr\SimpleCache\CacheInterface;
8-
use Rabbit\Base\Table\Table;
98
use Rabbit\Parser\ParserInterface;
9+
use Swoole\Table;
1010

11-
/**
12-
* Class TableCache
13-
* @package Rabbit\Cache
14-
*/
1511
class TableCache extends AbstractCache implements CacheInterface
1612
{
1713
private Table $tableInstance;
1814
private int $maxLive = 3000000;
19-
private float $gcSleep = 0.01;
15+
private int $gcSleep = 100;
2016
private int $gcProbability = 100;
2117

22-
/**
23-
* TableCache constructor.
24-
* @param int $size
25-
* @param int $dataLength
26-
* @param ParserInterface|null $serializer
27-
*/
2818
public function __construct(int $size = 1024, private int $dataLength = 8192, private ?ParserInterface $serializer = null)
2919
{
3020
parent::__construct();
31-
$this->tableInstance = $this->initCacheTable($size, $dataLength);
32-
}
33-
34-
/**
35-
* @param int $size
36-
* @param int $dataLength
37-
* @return Table
38-
*/
39-
private function initCacheTable(int $size, int $dataLength): Table
40-
{
41-
$table = new Table('cache', $size);
21+
$table = new Table($size);
4222
$table->column('expire', Table::TYPE_STRING, 11);
4323
$table->column('nextId', Table::TYPE_STRING, 35);
4424
$table->column('data', Table::TYPE_STRING, $dataLength);
4525
$table->create();
46-
return $table;
26+
$this->tableInstance = $table;
4727
}
4828

4929
public function get($key, mixed $default = null): mixed
@@ -121,17 +101,20 @@ private function gc(bool $force = false): void
121101
{
122102
if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
123103
$i = 100000;
124-
$table = $this->tableInstance->table;
125-
foreach ($table as $key => $column) {
104+
$dels = [];
105+
foreach ($this->tableInstance as $key => $column) {
126106
if ($column['expire'] > 0 && $column['expire'] < time()) {
127-
$this->deleteValue($key);
107+
$dels[] = $key;
128108
}
129109
$i--;
130110
if ($i <= 0) {
131-
\Swoole\Coroutine::sleep($this->gcSleep);
111+
usleep($this->gcSleep);
132112
$i = 100000;
133113
}
134114
}
115+
foreach ($dels as $key) {
116+
$this->deleteValue($key);
117+
}
135118
}
136119
}
137120

@@ -175,7 +158,7 @@ public function delete($key): bool
175158
public function clear(): bool
176159
{
177160
$table = [];
178-
foreach ($this->tableInstance->table as $key => $column) {
161+
foreach ($this->tableInstance as $key => $column) {
179162
$table[] = $key;
180163
}
181164
$ret = true;

0 commit comments

Comments
 (0)