2020-11-03 21:02:24 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
namespace ZM\Store;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
use Exception;
|
|
|
|
|
use Swoole\Table;
|
2020-12-14 01:24:34 +08:00
|
|
|
use ZM\Exception\ZMException;
|
2020-11-03 21:02:24 +08:00
|
|
|
|
|
|
|
|
class LightCacheInside
|
|
|
|
|
{
|
|
|
|
|
/** @var Table[]|null */
|
|
|
|
|
private static $kv_table = [];
|
|
|
|
|
|
|
|
|
|
public static $last_error = '';
|
|
|
|
|
|
|
|
|
|
public static function init() {
|
2020-12-14 01:24:34 +08:00
|
|
|
self::$kv_table["wait_api"] = new Table(3, 0);
|
2020-11-03 21:02:24 +08:00
|
|
|
self::$kv_table["wait_api"]->column("value", Table::TYPE_STRING, 65536);
|
2020-12-14 01:24:34 +08:00
|
|
|
self::$kv_table["connect"] = new Table(8, 0);
|
|
|
|
|
self::$kv_table["connect"]->column("value", Table::TYPE_STRING, 256);
|
|
|
|
|
$result = self::$kv_table["wait_api"]->create() && self::$kv_table["connect"]->create();
|
2020-11-03 21:02:24 +08:00
|
|
|
if ($result === false) {
|
|
|
|
|
self::$last_error = '系统内存不足,申请失败';
|
2021-01-29 23:34:34 +08:00
|
|
|
return false;
|
|
|
|
|
} else {
|
|
|
|
|
return true;
|
2020-11-03 21:02:24 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-14 01:24:34 +08:00
|
|
|
/**
|
|
|
|
|
* @param string $table
|
|
|
|
|
* @param string $key
|
|
|
|
|
* @return mixed|null
|
|
|
|
|
* @throws ZMException
|
|
|
|
|
*/
|
2020-11-03 21:02:24 +08:00
|
|
|
public static function get(string $table, string $key) {
|
2020-12-14 01:24:34 +08:00
|
|
|
if (!isset(self::$kv_table[$table])) throw new ZMException("not initialized LightCache");
|
2020-11-03 21:02:24 +08:00
|
|
|
$r = self::$kv_table[$table]->get($key);
|
|
|
|
|
return $r === false ? null : json_decode($r["value"], true);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @param string $table
|
|
|
|
|
* @param string $key
|
|
|
|
|
* @param string|array|int $value
|
|
|
|
|
* @return mixed
|
2020-12-14 01:24:34 +08:00
|
|
|
* @throws ZMException
|
2020-11-03 21:02:24 +08:00
|
|
|
*/
|
|
|
|
|
public static function set(string $table, string $key, $value) {
|
2020-12-14 01:24:34 +08:00
|
|
|
if (self::$kv_table === null) throw new ZMException("not initialized LightCache");
|
2020-11-03 21:02:24 +08:00
|
|
|
try {
|
|
|
|
|
return self::$kv_table[$table]->set($key, [
|
|
|
|
|
"value" => json_encode($value, 256)
|
|
|
|
|
]);
|
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static function unset(string $table, string $key) {
|
|
|
|
|
return self::$kv_table[$table]->del($key);
|
|
|
|
|
}
|
|
|
|
|
}
|