136 lines
3.2 KiB
PHP
136 lines
3.2 KiB
PHP
<?php
|
|
namespace app;
|
|
|
|
class DbCoroutineContext
|
|
{
|
|
// 协程隔离数据
|
|
protected static array $data = [];
|
|
protected static array $list = [];
|
|
|
|
// 普通环境全局数据
|
|
protected static array $globalData = [];
|
|
protected static array $globalList = [];
|
|
|
|
protected static function getCid(): ?int
|
|
{
|
|
if (class_exists('\Swoole\Coroutine')) {
|
|
$cid = \Swoole\Coroutine::getCid();
|
|
if ($cid >= 0) {
|
|
return $cid;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// put 存数据到 list
|
|
public static function put(mixed $value): void
|
|
{
|
|
$val = self::get('startTrans');
|
|
if (!empty($val) && $val === true) {
|
|
$value->startTrans();
|
|
}
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
self::$list[$cid][] = $value;
|
|
} else {
|
|
self::$globalList[] = $value;
|
|
}
|
|
}
|
|
|
|
// set 设置 key-value
|
|
public static function set(string $key, mixed $value): void
|
|
{
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
self::$data[$cid][$key] = $value;
|
|
} else {
|
|
self::$globalData[$key] = $value;
|
|
}
|
|
}
|
|
|
|
// get 获取 key-value
|
|
public static function get(string $key, mixed $default = null): mixed
|
|
{
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
return self::$data[$cid][$key] ?? $default;
|
|
} else {
|
|
return self::$globalData[$key] ?? $default;
|
|
}
|
|
}
|
|
|
|
// 获取 list
|
|
public static function getList(): array
|
|
{
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
return self::$list[$cid] ?? [];
|
|
} else {
|
|
return self::$globalList;
|
|
}
|
|
}
|
|
|
|
// 删除指定 key
|
|
public static function delete(string $key): void
|
|
{
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
unset(self::$data[$cid][$key]);
|
|
} else {
|
|
unset(self::$globalData[$key]);
|
|
}
|
|
}
|
|
|
|
public static function clearList()
|
|
{
|
|
foreach (self::getList() as $conn) {
|
|
try {
|
|
$conn->query('SELECT 1');
|
|
$conn->close();
|
|
// 连接正常
|
|
} catch (\Exception $e) {
|
|
}
|
|
}
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
unset(self::$list[$cid]);
|
|
} else {
|
|
self::$globalList = [];
|
|
}
|
|
}
|
|
|
|
public static function rollback()
|
|
{
|
|
foreach (self::getList() as $conn) {
|
|
$conn->rollback();
|
|
}
|
|
}
|
|
|
|
// 清理当前上下文
|
|
public static function clear(): void
|
|
{
|
|
foreach (self::getList() as $conn) {
|
|
try {
|
|
$conn->query('SELECT 1');
|
|
$conn->close();
|
|
// 连接正常
|
|
} catch (\Exception $e) {
|
|
}
|
|
}
|
|
$cid = self::getCid();
|
|
if ($cid !== null) {
|
|
unset(self::$data[$cid], self::$list[$cid]);
|
|
} else {
|
|
self::$globalData = [];
|
|
self::$globalList = [];
|
|
}
|
|
}
|
|
|
|
public static function commit()
|
|
{
|
|
foreach (self::getList() as $conn) {
|
|
$conn->commit();
|
|
}
|
|
}
|
|
}
|