zhamao-framework/src/ZM/Store/LightCacheInside.php

75 lines
2.1 KiB
PHP
Raw Normal View History

2020-11-03 21:02:24 +08:00
<?php
declare(strict_types=1);
2020-11-03 21:02:24 +08:00
namespace ZM\Store;
use Exception;
use Swoole\Table;
2023-06-12 18:33:06 +08:00
use ZM\Config\ZMConfig;
2021-09-01 14:14:00 +08:00
use ZM\Exception\LightCacheException;
use ZM\Exception\ZMException;
2020-11-03 21:02:24 +08:00
class LightCacheInside
{
/** @var null|Table[] */
2020-11-03 21:02:24 +08:00
private static $kv_table = [];
public static function init(): bool
{
try {
2023-06-05 13:50:57 +08:00
$size = ZMConfig::get('global', 'runtime')['inside_table_size'] ?? 65536;
self::createTable('wait_api', 3, $size);
self::createTable('connect', 3, 64); // 用于存单机器人模式下的机器人fd的
self::createTable('static_route', 64, 256); // 用于存储
self::createTable('light_array', 8, 512, 0.6);
} catch (ZMException $e) {
return false;
} // 用于存协程等待的状态内容的
// self::createTable("worker_start", 2, 1024);//用于存启动服务器时的状态的
return true;
2020-11-03 21:02:24 +08:00
}
/**
* @return null|mixed
*/
public static function get(string $table, string $key)
{
2020-11-03 21:02:24 +08:00
$r = self::$kv_table[$table]->get($key);
return $r === false ? null : json_decode($r['value'], true);
2020-11-03 21:02:24 +08:00
}
/**
2022-04-02 23:37:22 +08:00
* @param array|int|string $value
2020-11-03 21:02:24 +08:00
*/
public static function set(string $table, string $key, $value): bool
{
2020-11-03 21:02:24 +08:00
try {
return self::$kv_table[$table]->set($key, [
'value' => json_encode($value, 256),
2020-11-03 21:02:24 +08:00
]);
} catch (Exception $e) {
return false;
}
}
public static function unset(string $table, string $key)
{
2020-11-03 21:02:24 +08:00
return self::$kv_table[$table]->del($key);
}
/**
2022-04-02 23:37:22 +08:00
* @param float|int $conflict_proportion
* @throws ZMException
*/
2022-04-02 23:37:22 +08:00
private static function createTable(string $name, int $size, int $str_size, $conflict_proportion = 0)
{
self::$kv_table[$name] = new Table($size, $conflict_proportion);
self::$kv_table[$name]->column('value', Table::TYPE_STRING, $str_size);
$r = self::$kv_table[$name]->create();
if ($r === false) {
throw new LightCacheException('E00050', '内存不足,创建静态表失败!');
}
}
2020-11-03 21:02:24 +08:00
}