This commit is contained in:
2025-08-13 16:27:39 +08:00
parent 0d93c2570a
commit 17ad88608b
8 changed files with 1206 additions and 68 deletions

View File

@@ -1,13 +1,12 @@
<?php <?php
namespace app\model; namespace app\common\library;
use app\DbCoroutineContext; use app\DbCoroutineContext;
use think\Collection; use think\Collection;
use think\db\Connection; use think\db\Connection;
use think\facade\Cache;
use think\facade\Db; use think\facade\Db;
use think\facade\Log; use support\Log;
class DatabaseRoute class DatabaseRoute
{ {
@@ -29,7 +28,7 @@ class DatabaseRoute
int $count = null, int $count = null,
): array ): array
{ {
$dbMap = config('database.db_map'); $dbMap = config('think-orm.db_map');
$counts = []; $counts = [];
$total = 0; $total = 0;
@@ -192,7 +191,7 @@ class DatabaseRoute
bool $isRecords = false bool $isRecords = false
): array ): array
{ {
$dbMap = config('database.db_map'); $dbMap = config('think-orm.db_map');
$counts = []; $counts = [];
$total = 0; $total = 0;
@@ -367,7 +366,7 @@ class DatabaseRoute
*/ */
public static function deleteAllDbDirect(string $table, \Closure $builder): int public static function deleteAllDbDirect(string $table, \Closure $builder): int
{ {
$dbMap = config('database.db_master_map'); $dbMap = config('think-orm.db_master_map');
$totalDeleted = 0; $totalDeleted = 0;
foreach ($dbMap as $connName) { foreach ($dbMap as $connName) {
@@ -396,8 +395,8 @@ class DatabaseRoute
{ {
$this->table = $table; $this->table = $table;
$this->builder = $builder; $this->builder = $builder;
$this->dbMap = config('database.db_map'); $this->dbMap = config('think-orm.db_map');
$this->masterDbMap = config('database.db_master_map'); $this->masterDbMap = config('think-orm.db_master_map');
} }
public function __call($method, $args) public function __call($method, $args)
@@ -473,12 +472,12 @@ class DatabaseRoute
private static function getIndex() private static function getIndex()
{ {
$INDEX = \cache('db_index'); $INDEX = cache('db_index');
if ($INDEX == null) { if ($INDEX == null) {
$INDEX = 0; $INDEX = 0;
} }
$INDEX = ++$INDEX % 4; $INDEX = ++$INDEX % 4;
\cache('db_index', $INDEX); cache('db_index', $INDEX);
return $INDEX; return $INDEX;
} }
@@ -492,7 +491,12 @@ class DatabaseRoute
*/ */
public static function getConnection($table, $data = [], $isWrite = false) public static function getConnection($table, $data = [], $isWrite = false)
{ {
$routeConfig = config('think-orm.route'); $routeConfig = config('think-orm.route');
if (!isset($routeConfig[$table])) {
return $isWrite ? 'duanju-master' : 'duanju-slave';
}
$keyField = strpos($table, 'user') !== false || in_array($table, [ $keyField = strpos($table, 'user') !== false || in_array($table, [
'orders', 'course_collect', 'pay_details', 'disc_spinning_record', 'orders', 'course_collect', 'pay_details', 'disc_spinning_record',
'cash_out', 'course_user', 'tb_user', 'task_center_record', 'cash_out', 'course_user', 'tb_user', 'task_center_record',
@@ -502,7 +506,7 @@ class DatabaseRoute
if (!isset($data[$keyField])) { if (!isset($data[$keyField])) {
Log::warning("分库警告: 表={$table}, 数据中缺少 {$keyField} 字段"); Log::warning("分库警告: 表={$table}, 数据中缺少 {$keyField} 字段");
return $isWrite ? 'duanju_master' : 'duanju_slave'; return $isWrite ? 'duanju-master' : 'duanju-slave';
} }
$index = abs($data[$keyField] % 5); $index = abs($data[$keyField] % 5);
@@ -511,6 +515,19 @@ class DatabaseRoute
: $routeConfig[$table]['slave']; : $routeConfig[$table]['slave'];
$connectionName = str_replace("{\${$keyField}%5}", $index, $connectionTemplate); $connectionName = str_replace("{\${$keyField}%5}", $index, $connectionTemplate);
if (strpos($connectionName, 'slave')) {
$INDEX = self::getIndex();
$connectionName = str_replace("duanju", 'duanju'.$INDEX, $connectionName);
}
// 验证连接是否存在
$connections = config('think-orm.connections');
if (!isset($connections[$connectionName])) {
Log::error("分库错误: 表={$table}, 连接={$connectionName} 不存在");
return $isWrite ? 'duanju-master' : 'duanju-slave';
}
// Log::info("分库成功: 表={$table}, 键={$keyField}, 值={$data[$keyField]}, 索引={$index}, 连接={$connectionName}");
return $connectionName; return $connectionName;
} }
} }

View File

@@ -5,18 +5,16 @@ namespace app\controller;
use app\api\model\CourseCollect; use app\api\model\CourseCollect;
use app\api\model\CourseDetails; use app\api\model\CourseDetails;
use app\api\model\TbUser; use app\api\model\TbUser;
use app\model\DatabaseRoute; use app\common\library\DatabaseRoute;
use app\model\Test; use app\model\Test;
use support\Request; use support\Request;
use think\facade\Db; use think\facade\Db;
use think\facade\Log;
class IndexController class IndexController
{ {
public function index(Request $request) public function index(Request $request)
{ {
\support\Log::info('来了' . date('Y-m-d H:i:s'));
$get['courseId'] = $course_id = '1877654905222135809'; $get['courseId'] = $course_id = '1877654905222135809';
$user['user_id'] = $user_id = '14240'; $user['user_id'] = $user_id = '14240';
$user = DatabaseRoute::getDb('tb_user', $user_id)->find(); $user = DatabaseRoute::getDb('tb_user', $user_id)->find();
@@ -132,6 +130,7 @@ class IndexController
$detailsId = $det_db->name('course_user')->where(['course_id' => $courseId, 'classify' => 2])->column('course_details_id'); $detailsId = $det_db->name('course_user')->where(['course_id' => $courseId, 'classify' => 2])->column('course_details_id');
$det_db->close(); $det_db->close();
$detailsId = array_flip(array_flip($detailsId)); // 去重 $detailsId = array_flip(array_flip($detailsId)); // 去重
\support\Log::info('啦啦啦' . date('Y-m-d H:i:s'));
} }
// 处理剧集列表 // 处理剧集列表
$current = null; $current = null;
@@ -162,7 +161,6 @@ class IndexController
->where('classify', 2) ->where('classify', 2)
->limit(1) ->limit(1)
->count(); ->count();
$isGood_db->close();
$s['isGood'] = empty($isGood) || $isGood == 0 ? 0 : 1; $s['isGood'] = empty($isGood) || $isGood == 0 ? 0 : 1;
} }
} }
@@ -184,6 +182,7 @@ class IndexController
'collect' => empty($collect) || $collect == 0 ? 0 : 1, 'collect' => empty($collect) || $collect == 0 ? 0 : 1,
'list' => $courseDetailsSetVos 'list' => $courseDetailsSetVos
]; ];
\support\Log::info('即将返回' . date('Y-m-d H:i:s'));
return json($map); return json($map);
} catch (\Exception $e) { } catch (\Exception $e) {
return json($e->getMessage()); return json($e->getMessage());

View File

@@ -2,8 +2,10 @@
namespace app\model; namespace app\model;
use support\Log;
use think\model; use think\model;
use think\facade\Db; use think\facade\Db;
use app\common\library\DatabaseRoute;
class Test extends Model class Test extends Model
{ {
@@ -51,7 +53,7 @@ class Test extends Model
}else{ }else{
$isExpire = true; $isExpire = true;
} }
Log::info('嘿嘿' . date('Y-m-d H:i:s'));
return !$isExpire; return !$isExpire;
} }

View File

@@ -28,7 +28,8 @@
"workerman/webman-framework": "^2.1", "workerman/webman-framework": "^2.1",
"monolog/monolog": "^2.0", "monolog/monolog": "^2.0",
"webman/think-orm": "^2.1", "webman/think-orm": "^2.1",
"vlucas/phpdotenv": "^5.6" "vlucas/phpdotenv": "^5.6",
"webman/think-cache": "^2.1"
}, },
"suggest": { "suggest": {
"ext-event": "For better performance. " "ext-event": "For better performance. "

44
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "31b009f9f2392b9eda909c76dbca259f", "content-hash": "c2aa9244f1a0947409551191f357b155",
"packages": [ "packages": [
{ {
"name": "graham-campbell/result-type", "name": "graham-campbell/result-type",
@@ -1059,6 +1059,48 @@
], ],
"time": "2024-07-20T21:52:34+00:00" "time": "2024-07-20T21:52:34+00:00"
}, },
{
"name": "webman/think-cache",
"version": "v2.1.1",
"source": {
"type": "git",
"url": "https://github.com/webman-php/think-cache.git",
"reference": "807d86942850d5755bf296967abbae48f3b7e176"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/webman-php/think-cache/zipball/807d86942850d5755bf296967abbae48f3b7e176",
"reference": "807d86942850d5755bf296967abbae48f3b7e176",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"psr/simple-cache": "^1.0|^2.0|^3.0",
"topthink/think-container": "^2.0|^3.0",
"workerman/webman-framework": "^2.1 || dev-master"
},
"type": "library",
"autoload": {
"psr-4": {
"support\\": "src/support",
"Webman\\ThinkCache\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"support": {
"issues": "https://github.com/webman-php/think-cache/issues",
"source": "https://github.com/webman-php/think-cache/tree/v2.1.1"
},
"time": "2025-03-18T06:08:37+00:00"
},
{ {
"name": "webman/think-orm", "name": "webman/think-orm",
"version": "v2.1.6", "version": "v2.1.6",

View File

@@ -26,7 +26,7 @@ return [
'user' => '', 'user' => '',
'group' => '', 'group' => '',
'reusePort' => false, 'reusePort' => false,
'eventLoop' => \Workerman\Events\Swoole::class, 'eventLoop' => '',
'context' => [], 'context' => [],
'constructor' => [ 'constructor' => [
'requestClass' => Request::class, 'requestClass' => Request::class,

39
config/think-cache.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
return [
// 默认缓存驱动
'default' => 'redis',
// 缓存连接方式配置
'stores' => [
// redis缓存
'redis' => [
// 驱动方式
'type' => 'redis',
// 服务器地址
'host' => '127.0.0.1',
// 缓存前缀
'prefix' => 'cache:',
'password' => '222222',
// 默认缓存有效期 0表示永久缓存
'expire' => 0,
// Thinkphp官方没有这个参数由于生成的tag键默认不过期如果tag键数量很大避免长时间占用内存可以设置一个超过其他缓存的过期时间0为不设置
'tag_expire' => 86400 * 30,
// 缓存标签前缀
'tag_prefix' => 'tag:',
// 连接池配置
'pool' => [
'max_connections' => 5, // 最大连接数
'min_connections' => 1, // 最小连接数
'wait_timeout' => 3, // 从连接池获取连接等待超时时间
'idle_timeout' => 60, // 连接最大空闲时间,超过该时间会被回收
'heartbeat_interval' => 50, // 心跳检测间隔需要小于60秒
],
],
// 文件缓存
'file' => [
// 驱动方式
'type' => 'file',
// 设置不同的缓存保存目录
'path' => runtime_path() . '/file/',
],
],
];

File diff suppressed because it is too large Load Diff