add cs fixer and PHPStan and activate it (build 436)

This commit is contained in:
crazywhalecc
2022-03-15 18:05:33 +08:00
parent d01bd69aa5
commit 1706afbcd0
163 changed files with 4572 additions and 3588 deletions

View File

@@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
namespace ZM\Store;
use Exception;
use Swoole\Table;
use ZM\Annotation\Swoole\OnSave;
@@ -12,140 +12,156 @@ use ZM\Event\EventDispatcher;
use ZM\Exception\LightCacheException;
use ZM\Exception\ZMException;
use ZM\Framework;
use ZM\Utils\Manager\ProcessManager;
use ZM\Utils\Manager\WorkerManager;
class LightCache
{
/** @var Table|null */
private static $kv_table = null;
public static $last_error = '';
/** @var null|Table */
private static $kv_table;
private static $config = [];
public static $last_error = '';
/**
* @param $config
* @return bool|mixed
* @throws Exception
* @return bool|mixed
*/
public static function init($config) {
public static function init($config)
{
self::$config = $config;
self::$kv_table = new Table($config["size"], $config["hash_conflict_proportion"]);
self::$kv_table->column("value", Table::TYPE_STRING, $config["max_strlen"]);
self::$kv_table->column("expire", Table::TYPE_INT);
self::$kv_table->column("data_type", Table::TYPE_STRING, 8);
self::$kv_table = new Table($config['size'], $config['hash_conflict_proportion']);
self::$kv_table->column('value', Table::TYPE_STRING, $config['max_strlen']);
self::$kv_table->column('expire', Table::TYPE_INT);
self::$kv_table->column('data_type', Table::TYPE_STRING, 8);
$result = self::$kv_table->create();
// 加载内容
if ($result === true && isset($config["persistence_path"])) {
if (file_exists($config["persistence_path"])) {
$r = json_decode(file_get_contents($config["persistence_path"]), true);
if ($r === null) $r = [];
if ($result === true && isset($config['persistence_path'])) {
if (file_exists($config['persistence_path'])) {
$r = json_decode(file_get_contents($config['persistence_path']), true);
if ($r === null) {
$r = [];
}
foreach ($r as $k => $v) {
$write = self::set($k, $v);
Console::verbose("Writing LightCache: " . $k);
Console::verbose('Writing LightCache: ' . $k);
if ($write === false) {
self::$last_error = zm_internal_errcode("E00051") . '可能是由于 Hash 冲突过多导致动态空间无法分配内存';
self::$last_error = zm_internal_errcode('E00051') . '可能是由于 Hash 冲突过多导致动态空间无法分配内存';
return false;
}
}
}
}
if ($result === false) {
self::$last_error = zm_internal_errcode("E00050") . '系统内存不足,申请失败';
self::$last_error = zm_internal_errcode('E00050') . '系统内存不足,申请失败';
} else {
$obj = Framework::loadFrameworkState();
foreach (($obj["expiring_light_cache"] ?? []) as $k => $v) {
$value = $v["value"];
foreach (($obj['expiring_light_cache'] ?? []) as $k => $v) {
$value = $v['value'];
if (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
if (strlen($value) >= self::$config["max_strlen"]) return false;
$data_type = "json";
if (strlen($value) >= self::$config['max_strlen']) {
return false;
}
$data_type = 'json';
} elseif (is_string($value)) {
$data_type = "";
$data_type = '';
} elseif (is_int($value)) {
$data_type = "int";
$data_type = 'int';
} elseif (is_bool($value)) {
$data_type = "bool";
$data_type = 'bool';
$value = json_encode($value);
} else {
return false;
}
$result = self::$kv_table->set($k, [
"value" => $value,
"expire" => $v["expire"],
"data_type" => $data_type
'value' => $value,
'expire' => $v['expire'],
'data_type' => $data_type,
]);
if ($result === false) return false;
if ($result === false) {
return false;
}
}
}
return $result;
}
/**
* @param string $key
* @return null|mixed
* @throws ZMException
* @return null|mixed
*/
public static function get(string $key) {
if (self::$kv_table === null) throw new LightCacheException("E00048", "not initialized LightCache");
public static function get(string $key)
{
if (self::$kv_table === null) {
throw new LightCacheException('E00048', 'not initialized LightCache');
}
self::checkExpire($key);
$r = self::$kv_table->get($key);
return $r === false ? null : self::parseGet($r);
}
/**
* @param string $key
* @return mixed|null
* @throws ZMException
* @return null|mixed
*/
public static function getExpire(string $key) {
if (self::$kv_table === null) throw new LightCacheException("E00048", "not initialized LightCache");
public static function getExpire(string $key)
{
if (self::$kv_table === null) {
throw new LightCacheException('E00048', 'not initialized LightCache');
}
self::checkExpire($key);
$r = self::$kv_table->get($key, "expire");
$r = self::$kv_table->get($key, 'expire');
return $r === false ? null : $r - time();
}
/**
* @param string $key
* @return mixed|null
* @throws ZMException
* @return null|mixed
* @since 2.4.3
*/
public static function getExpireTS(string $key) {
if (self::$kv_table === null) throw new LightCacheException("E00048", "not initialized LightCache");
public static function getExpireTS(string $key)
{
if (self::$kv_table === null) {
throw new LightCacheException('E00048', 'not initialized LightCache');
}
self::checkExpire($key);
$r = self::$kv_table->get($key, "expire");
$r = self::$kv_table->get($key, 'expire');
return $r === false ? null : $r;
}
/**
* @param string $key
* @param string|array|int $value
* @param int $expire
* @return mixed
* @param array|int|string $value
* @throws ZMException
* @return bool
*/
public static function set(string $key, $value, int $expire = -1) {
if (self::$kv_table === null) throw new LightCacheException("E00048", "not initialized LightCache");
public static function set(string $key, $value, int $expire = -1)
{
if (self::$kv_table === null) {
throw new LightCacheException('E00048', 'not initialized LightCache');
}
if (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
if (strlen($value) >= self::$config["max_strlen"]) return false;
$data_type = "json";
if (strlen($value) >= self::$config['max_strlen']) {
return false;
}
$data_type = 'json';
} elseif (is_string($value)) {
$data_type = "";
$data_type = '';
} elseif (is_int($value)) {
$data_type = "int";
$data_type = 'int';
} elseif (is_bool($value)) {
$data_type = "bool";
$data_type = 'bool';
$value = json_encode($value);
} else {
throw new LightCacheException("E00049", "Only can set string, array and int");
throw new LightCacheException('E00049', 'Only can set string, array and int');
}
try {
return self::$kv_table->set($key, [
"value" => $value,
"expire" => $expire >= 0 ? $expire + time() : $expire,
"data_type" => $data_type
'value' => $value,
'expire' => $expire >= 0 ? $expire + time() : $expire,
'data_type' => $data_type,
]);
} catch (Exception $e) {
return false;
@@ -153,57 +169,65 @@ class LightCache
}
/**
* @param string $key
* @param $value
* @return bool|mixed
* @throws ZMException
* @return bool
*/
public static function update(string $key, $value) {
if (self::$kv_table === null) throw new LightCacheException("E00048", "not initialized LightCache.");
public static function update(string $key, $value)
{
if (self::$kv_table === null) {
throw new LightCacheException('E00048', 'not initialized LightCache.');
}
if (is_array($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
if (strlen($value) >= self::$config["max_strlen"]) return false;
$data_type = "json";
if (strlen($value) >= self::$config['max_strlen']) {
return false;
}
$data_type = 'json';
} elseif (is_string($value)) {
$data_type = "";
$data_type = '';
} elseif (is_int($value)) {
$data_type = "int";
$data_type = 'int';
} else {
throw new LightCacheException("E00048", "Only can set string, array and int");
throw new LightCacheException('E00048', 'Only can set string, array and int');
}
try {
if (self::$kv_table->get($key) === false) return false;
if (self::$kv_table->get($key) === false) {
return false;
}
return self::$kv_table->set($key, [
"value" => $value,
"data_type" => $data_type
'value' => $value,
'data_type' => $data_type,
]);
} catch (Exception $e) {
return false;
}
}
public static function getMemoryUsage() {
public static function getMemoryUsage()
{
return self::$kv_table->getMemorySize();
}
/**
* @param string $key
* @return bool
* @throws Exception
*/
public static function isset(string $key): bool {
public static function isset(string $key): bool
{
return self::get($key) !== null;
}
public static function unset(string $key) {
public static function unset(string $key)
{
return self::$kv_table->del($key);
}
public static function getAll(): array {
public static function getAll(): array
{
$r = [];
$del = [];
foreach (self::$kv_table as $k => $v) {
if ($v["expire"] <= time() && $v["expire"] >= 0) {
if ($v['expire'] <= time() && $v['expire'] >= 0) {
$del[] = $k;
continue;
}
@@ -215,69 +239,81 @@ class LightCache
return $r;
}
public static function addPersistence($key) {
if (file_exists(self::$config["persistence_path"])) {
$r = json_decode(file_get_contents(self::$config["persistence_path"]), true);
if ($r === null) $r = [];
if (!isset($r[$key])) $r[$key] = null;
file_put_contents(self::$config["persistence_path"], json_encode($r, 64 | 128 | 256));
public static function addPersistence($key)
{
if (file_exists(self::$config['persistence_path'])) {
$r = json_decode(file_get_contents(self::$config['persistence_path']), true);
if ($r === null) {
$r = [];
}
if (!isset($r[$key])) {
$r[$key] = null;
}
file_put_contents(self::$config['persistence_path'], json_encode($r, 64 | 128 | 256));
return true;
} else {
return false;
}
return false;
}
public static function removePersistence($key) {
if (file_exists(self::$config["persistence_path"])) {
$r = json_decode(file_get_contents(self::$config["persistence_path"]), true);
if ($r === null) $r = [];
if (isset($r[$key])) unset($r[$key]);
file_put_contents(self::$config["persistence_path"], json_encode($r, 64 | 128 | 256));
public static function removePersistence($key)
{
if (file_exists(self::$config['persistence_path'])) {
$r = json_decode(file_get_contents(self::$config['persistence_path']), true);
if ($r === null) {
$r = [];
}
if (isset($r[$key])) {
unset($r[$key]);
}
file_put_contents(self::$config['persistence_path'], json_encode($r, 64 | 128 | 256));
return true;
} else {
return false;
}
return false;
}
/**
* 这个只能在唯一一个工作进程中执行
* @throws Exception
*/
public static function savePersistence() {
public static function savePersistence()
{
if (server()->worker_id !== MAIN_WORKER) {
ProcessManager::sendActionToWorker(MAIN_WORKER, "save_persistence", []);
WorkerManager::sendActionToWorker(MAIN_WORKER, 'save_persistence', []);
return;
}
$dispatcher = new EventDispatcher(OnSave::class);
$dispatcher->dispatchEvents();
if (self::$kv_table === null) return;
if (self::$kv_table === null) {
return;
}
if (!empty(self::$config["persistence_path"])) {
if (file_exists(self::$config["persistence_path"])) {
$r = json_decode(file_get_contents(self::$config["persistence_path"]), true);
if (!empty(self::$config['persistence_path'])) {
if (file_exists(self::$config['persistence_path'])) {
$r = json_decode(file_get_contents(self::$config['persistence_path']), true);
} else {
$r = [];
}
if ($r === null) $r = [];
if ($r === null) {
$r = [];
}
foreach ($r as $k => $v) {
Console::verbose("Saving " . $k);
Console::verbose('Saving ' . $k);
$r[$k] = self::get($k);
}
file_put_contents(self::$config["persistence_path"], json_encode($r, 64 | 128 | 256));
file_put_contents(self::$config['persistence_path'], json_encode($r, 64 | 128 | 256));
}
$obj = Framework::loadFrameworkState();
$obj["expiring_light_cache"] = [];
$obj['expiring_light_cache'] = [];
$del = [];
foreach (self::$kv_table as $k => $v) {
if ($v["expire"] <= time() && $v["expire"] >= 0) {
if ($v['expire'] <= time() && $v['expire'] >= 0) {
$del[] = $k;
continue;
} elseif ($v["expire"] > time()) {
$obj["expiring_light_cache"][$k] = [
"expire" => $v["expire"],
"value" => self::parseGet($v)
} elseif ($v['expire'] > time()) {
$obj['expiring_light_cache'][$k] = [
'expire' => $v['expire'],
'value' => self::parseGet($v),
];
}
}
@@ -285,26 +321,28 @@ class LightCache
self::unset($v);
}
Framework::saveFrameworkState($obj);
Console::verbose("Saved.");
Console::verbose('Saved.');
}
private static function checkExpire($key) {
if (($expire = self::$kv_table->get($key, "expire")) >= 0) {
private static function checkExpire($key)
{
if (($expire = self::$kv_table->get($key, 'expire')) >= 0) {
if ($expire <= time()) {
self::$kv_table->del($key);
}
}
}
private static function parseGet($r) {
switch ($r["data_type"]) {
case "json":
case "int":
case "bool":
return json_decode($r["value"], true);
case "":
private static function parseGet($r)
{
switch ($r['data_type']) {
case 'json':
case 'int':
case 'bool':
return json_decode($r['value'], true);
case '':
default:
return $r["value"];
return $r['value'];
}
}
}

View File

@@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
namespace ZM\Store;
use Exception;
use Swoole\Table;
use ZM\Exception\LightCacheException;
@@ -11,15 +11,16 @@ use ZM\Exception\ZMException;
class LightCacheInside
{
/** @var Table[]|null */
/** @var null|Table[] */
private static $kv_table = [];
public static function init(): bool {
public static function init(): bool
{
try {
self::createTable("wait_api", 3, 65536);
self::createTable("connect", 3, 64); //用于存单机器人模式下的机器人fd的
self::createTable("static_route", 64, 256);//用于存储
self::createTable("light_array", 8, 512, 0.6);
self::createTable('wait_api', 3, 65536);
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;
} //用于存协程等待的状态内容的
@@ -28,32 +29,31 @@ class LightCacheInside
}
/**
* @param string $table
* @param string $key
* @return mixed|null
* @return null|mixed
*/
public static function get(string $table, string $key) {
public static function get(string $table, string $key)
{
$r = self::$kv_table[$table]->get($key);
return $r === false ? null : json_decode($r["value"], true);
return $r === false ? null : json_decode($r['value'], true);
}
/**
* @param string $table
* @param string $key
* @param string|array|int $value
* @param array|int|string $value
* @return mixed
*/
public static function set(string $table, string $key, $value): bool {
public static function set(string $table, string $key, $value): bool
{
try {
return self::$kv_table[$table]->set($key, [
"value" => json_encode($value, 256)
'value' => json_encode($value, 256),
]);
} catch (Exception $e) {
return false;
}
}
public static function unset(string $table, string $key) {
public static function unset(string $table, string $key)
{
return self::$kv_table[$table]->del($key);
}
@@ -61,13 +61,16 @@ class LightCacheInside
* @param $name
* @param $size
* @param $str_size
* @param int $conflict_proportion
* @param int $conflict_proportion
* @throws ZMException
*/
private static function createTable($name, $size, $str_size, $conflict_proportion = 0) {
private static function createTable($name, $size, $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);
self::$kv_table[$name]->column('value', Table::TYPE_STRING, $str_size);
$r = self::$kv_table[$name]->create();
if ($r === false) throw new LightCacheException("E00050", "内存不足,创建静态表失败!");
if ($r === false) {
throw new LightCacheException('E00050', '内存不足,创建静态表失败!');
}
}
}

View File

@@ -1,47 +1,56 @@
<?php /** @noinspection PhpUnused */
<?php
/** @noinspection PhpUnused */
declare(strict_types=1);
namespace ZM\Store\Lock;
use Swoole\Coroutine;
use Swoole\Coroutine\System;
use Swoole\Table;
use ZM\Console\Console;
class SpinLock
{
/** @var null|Table */
private static $kv_lock = null;
private static $kv_lock;
private static $delay = 1;
public static function init($key_cnt, $delay = 1) {
public static function init($key_cnt, $delay = 1)
{
self::$kv_lock = new Table($key_cnt, 0.7);
self::$delay = $delay;
self::$kv_lock->column('lock_num', Table::TYPE_INT, 8);
return self::$kv_lock->create();
}
public static function lock(string $key) {
public static function lock(string $key)
{
while (($r = self::$kv_lock->incr($key, 'lock_num')) > 1) { //此资源已经被锁上了
if (Coroutine::getCid() != -1) System::sleep(self::$delay / 1000);
else usleep(self::$delay * 1000);
if (Coroutine::getCid() != -1) {
System::sleep(self::$delay / 1000);
} else {
usleep(self::$delay * 1000);
}
}
}
public static function tryLock(string $key): bool {
public static function tryLock(string $key): bool
{
if (($r = self::$kv_lock->incr($key, 'lock_num')) > 1) {
return false;
}
return true;
}
public static function unlock(string $key) {
public static function unlock(string $key)
{
return self::$kv_lock->set($key, ['lock_num' => 0]);
}
public static function transaction(string $key, callable $function) {
public static function transaction(string $key, callable $function)
{
SpinLock::lock($key);
$function();
SpinLock::unlock($key);

View File

@@ -1,13 +1,13 @@
<?php
declare(strict_types=1);
namespace ZM\Store\MySQL;
use ZM\MySQL\MySQLPool;
class SqlPoolStorage
{
/** @var MySQLPool */
public static $sql_pool = null;
public static $sql_pool;
}

View File

@@ -1,7 +1,11 @@
<?php /** @noinspection PhpUnused */
<?php
/** @noinspection PhpComposerExtensionStubsInspection */
/**
* @noinspection PhpComposerExtensionStubsInspection
* @noinspection PhpUnused
*/
declare(strict_types=1);
namespace ZM\Store\Redis;
@@ -12,38 +16,48 @@ class ZMRedis
{
private $conn;
/**
* @param callable $callable
* @return mixed
* @throws NotInitializedException
*/
public static function call(callable $callable) {
if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized.");
$r = ZMRedisPool::$pool->get();
$result = $callable($r);
if (isset($r->wasted)) ZMRedisPool::$pool->put(null);
else ZMRedisPool::$pool->put($r);
return $result;
}
/**
* ZMRedis constructor.
* @throws NotInitializedException
*/
public function __construct() {
if (ZMRedisPool::$pool === null) throw new NotInitializedException("Redis pool is not initialized.");
public function __construct()
{
if (ZMRedisPool::$pool === null) {
throw new NotInitializedException('Redis pool is not initialized.');
}
$this->conn = ZMRedisPool::$pool->get();
}
/**
* @return Redis
*/
public function get(): Redis {
return $this->conn;
public function __destruct()
{
if (isset($this->conn->wasted)) {
ZMRedisPool::$pool->put(null);
} else {
ZMRedisPool::$pool->put($this->conn);
}
}
public function __destruct() {
if (isset($this->conn->wasted)) ZMRedisPool::$pool->put(null);
else ZMRedisPool::$pool->put($this->conn);
/**
* @throws NotInitializedException
* @return mixed
*/
public static function call(callable $callable)
{
if (ZMRedisPool::$pool === null) {
throw new NotInitializedException('Redis pool is not initialized.');
}
$r = ZMRedisPool::$pool->get();
$result = $callable($r);
if (isset($r->wasted)) {
ZMRedisPool::$pool->put(null);
} else {
ZMRedisPool::$pool->put($r);
}
return $result;
}
public function get(): Redis
{
return $this->conn;
}
}

View File

@@ -1,9 +1,11 @@
<?php /** @noinspection PhpComposerExtensionStubsInspection */
<?php
/** @noinspection PhpComposerExtensionStubsInspection */
declare(strict_types=1);
namespace ZM\Store\Redis;
use RedisException;
use Swoole\Database\RedisConfig;
use Swoole\Database\RedisPool;
@@ -12,25 +14,27 @@ use ZM\Console\Console;
class ZMRedisPool
{
/** @var null|RedisPool */
public static $pool = null;
public static $pool;
public static function init($config) {
self::$pool = new RedisPool((new RedisConfig())
->withHost($config['host'])
->withPort($config['port'])
->withAuth($config['auth'])
->withDbIndex($config['db_index'])
->withTimeout($config['timeout'] ?? 1)
public static function init($config)
{
self::$pool = new RedisPool(
(new RedisConfig())
->withHost($config['host'])
->withPort($config['port'])
->withAuth($config['auth'])
->withDbIndex($config['db_index'])
->withTimeout($config['timeout'] ?? 1)
);
try {
$r = self::$pool->get()->ping('123');
if (strpos(strtolower($r), "123") !== false) {
Console::debug("成功连接redis连接池");
if (strpos(strtolower($r), '123') !== false) {
Console::debug('成功连接redis连接池');
} else {
var_dump($r);
}
} catch (RedisException $e) {
Console::error(zm_internal_errcode("E00047") . "Redis init failed! " . $e->getMessage());
Console::error(zm_internal_errcode('E00047') . 'Redis init failed! ' . $e->getMessage());
self::$pool = null;
}
}

View File

@@ -1,96 +1,107 @@
<?php /** @noinspection PhpMissingReturnTypeInspection */
<?php
/** @noinspection PhpMissingReturnTypeInspection */
declare(strict_types=1);
namespace ZM\Store;
use ZM\Config\ZMConfig;
class WorkerCache
{
public static $config = null;
public static $config;
public static $store = [];
public static $transfer = [];
public static function get($key) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
public static function get($key)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
return self::$store[$key] ?? null;
} else {
$action = ["action" => "getWorkerCache", "key" => $key, "cid" => zm_cid()];
server()->sendMessage(json_encode($action, JSON_UNESCAPED_UNICODE), $config["worker"]);
zm_yield();
$p = self::$transfer[zm_cid()] ?? null;
unset(self::$transfer[zm_cid()]);
return $p;
}
}
public static function set($key, $value, $async = false) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
self::$store[$key] = $value;
return true;
} else {
$action = ["action" => $async ? "asyncSetWorkerCache" : "setWorkerCache", "key" => $key, "value" => $value, "cid" => zm_cid()];
return self::processRemote($action, $async, $config);
}
}
public static function hasKey($key, $subkey) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
return isset(self::$store[$key][$subkey]);
} else {
$action = ["hasKeyWorkerCache", "key" => $key, "subkey" => $subkey, "cid" => zm_cid()];
return self::processRemote($action, false, $config);
}
}
private static function processRemote($action, $async, $config) {
$ss = server()->sendMessage(json_encode($action, JSON_UNESCAPED_UNICODE), $config["worker"]);
if (!$ss) return false;
if ($async) return true;
$action = ['action' => 'getWorkerCache', 'key' => $key, 'cid' => zm_cid()];
server()->sendMessage(json_encode($action, JSON_UNESCAPED_UNICODE), $config['worker']);
zm_yield();
$p = self::$transfer[zm_cid()] ?? null;
unset(self::$transfer[zm_cid()]);
return $p;
}
public static function unset($key, $async = false) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
public static function set($key, $value, $async = false)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
self::$store[$key] = $value;
return true;
}
$action = ['action' => $async ? 'asyncSetWorkerCache' : 'setWorkerCache', 'key' => $key, 'value' => $value, 'cid' => zm_cid()];
return self::processRemote($action, $async, $config);
}
public static function hasKey($key, $subkey)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
return isset(self::$store[$key][$subkey]);
}
$action = ['hasKeyWorkerCache', 'key' => $key, 'subkey' => $subkey, 'cid' => zm_cid()];
return self::processRemote($action, false, $config);
}
public static function unset($key, $async = false)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
unset(self::$store[$key]);
return true;
} else {
$action = ["action" => $async ? "asyncUnsetWorkerCache" : "unsetWorkerCache", "key" => $key, "cid" => zm_cid()];
return self::processRemote($action, $async, $config);
}
$action = ['action' => $async ? 'asyncUnsetWorkerCache' : 'unsetWorkerCache', 'key' => $key, 'cid' => zm_cid()];
return self::processRemote($action, $async, $config);
}
public static function add($key, int $value, $async = false) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
if (!isset(self::$store[$key])) self::$store[$key] = 0;
public static function add($key, int $value, $async = false)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
if (!isset(self::$store[$key])) {
self::$store[$key] = 0;
}
self::$store[$key] += $value;
return true;
} else {
$action = ["action" => $async ? "asyncAddWorkerCache" : "addWorkerCache", "key" => $key, "value" => $value, "cid" => zm_cid()];
return self::processRemote($action, $async, $config);
}
$action = ['action' => $async ? 'asyncAddWorkerCache' : 'addWorkerCache', 'key' => $key, 'value' => $value, 'cid' => zm_cid()];
return self::processRemote($action, $async, $config);
}
public static function sub($key, int $value, $async = false) {
$config = self::$config ?? ZMConfig::get("global", "worker_cache") ?? ["worker" => 0];
if ($config["worker"] === server()->worker_id) {
if (!isset(self::$store[$key])) self::$store[$key] = 0;
public static function sub($key, int $value, $async = false)
{
$config = self::$config ?? ZMConfig::get('global', 'worker_cache') ?? ['worker' => 0];
if ($config['worker'] === server()->worker_id) {
if (!isset(self::$store[$key])) {
self::$store[$key] = 0;
}
self::$store[$key] -= $value;
return true;
} else {
$action = ["action" => $async ? "asyncSubWorkerCache" : "subWorkerCache", "key" => $key, "value" => $value, "cid" => zm_cid()];
return self::processRemote($action, $async, $config);
}
$action = ['action' => $async ? 'asyncSubWorkerCache' : 'subWorkerCache', 'key' => $key, 'value' => $value, 'cid' => zm_cid()];
return self::processRemote($action, $async, $config);
}
}
private static function processRemote($action, $async, $config)
{
$ss = server()->sendMessage(json_encode($action, JSON_UNESCAPED_UNICODE), $config['worker']);
if (!$ss) {
return false;
}
if ($async) {
return true;
}
zm_yield();
$p = self::$transfer[zm_cid()] ?? null;
unset(self::$transfer[zm_cid()]);
return $p;
}
}

View File

@@ -1,9 +1,9 @@
<?php
declare(strict_types=1);
namespace ZM\Store;
use Swoole\Atomic;
use ZM\Config\ZMConfig;
@@ -14,33 +14,34 @@ class ZMAtomic
/**
* @param $name
* @return Atomic|null
*/
public static function get($name): ?Atomic {
public static function get($name): ?Atomic
{
return self::$atomics[$name] ?? null;
}
/**
* 初始化atomic计数器
*/
public static function init() {
foreach ((ZMConfig::get("global", "init_atomics") ?? []) as $k => $v) {
public static function init()
{
foreach ((ZMConfig::get('global', 'init_atomics') ?? []) as $k => $v) {
self::$atomics[$k] = new Atomic($v);
}
self::$atomics["stop_signal"] = new Atomic(0);
self::$atomics["_int_is_reload"] = new Atomic(0);
self::$atomics["wait_msg_id"] = new Atomic(0);
self::$atomics["_event_id"] = new Atomic(0);
self::$atomics["server_is_stopped"] = new Atomic(0);
if (!defined("ZM_WORKER_NUM")) define("ZM_WORKER_NUM", 1);
for($i = 0; $i < ZM_WORKER_NUM; ++$i) {
self::$atomics["_#worker_".$i] = new Atomic(0);
self::$atomics['stop_signal'] = new Atomic(0);
self::$atomics['_int_is_reload'] = new Atomic(0);
self::$atomics['wait_msg_id'] = new Atomic(0);
self::$atomics['_event_id'] = new Atomic(0);
self::$atomics['server_is_stopped'] = new Atomic(0);
if (!defined('ZM_WORKER_NUM')) {
define('ZM_WORKER_NUM', 1);
}
for ($i = 0; $i < ZM_WORKER_NUM; ++$i) {
self::$atomics['_#worker_' . $i] = new Atomic(0);
}
for ($i = 0; $i < 10; ++$i) {
self::$atomics["_tmp_" . $i] = new Atomic(0);
self::$atomics['_tmp_' . $i] = new Atomic(0);
}
self::$atomics["ss"] = new Atomic(1);
self::$atomics['ss'] = new Atomic(1);
}
}

View File

@@ -1,4 +1,6 @@
<?php
declare(strict_types=1);
/**
* Created by PhpStorm.
* User: jerry
@@ -11,7 +13,10 @@ namespace ZM\Store;
class ZMBuf
{
public static $events = [];
public static $instance = [];
public static $context_class = [];
public static $terminal = null;
public static $terminal;
}