| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Service;
- use Illuminate\Support\Facades\Config;
- use Illuminate\Support\Facades\DB;
- class U8DatabaseServerService extends Service
- {
- public $db = null;
- public $error = null; // 错误信息
- private $database = "";
- private $connName = "";
- public function __construct($loginUser = [])
- {
- $this->database = $loginUser['zt_database'] ?? "";
- $this->connName = 'sqlsrv_' . $this->database . '_' . uniqid();
- $this->createConnection();
- }
- private function createConnection()
- {
- $mainConnName = $this->connName;
- // 创建连接
- $mainConfig = [
- 'driver' => 'sqlsrv',
- 'host' => env('SQLSRV_HOST'),
- 'port' => env('SQLSRV_PORT'),
- 'database' => $this->database,
- 'username' => env('SQLSRV_USERNAME'),
- 'password' => env('SQLSRV_PASSWORD'),
- 'options' => [
- \PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 15, // 减少超时
- \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
- ],
- ];
- // 配置注入
- Config::set("database.connections.{$mainConnName}", $mainConfig);
- // 连接
- $this->db = DB::connection($mainConnName);
- // 测试
- $this->validateConnection($this->db);
- // 如果失败,立即清理,避免残留连接名
- if ($this->error) {
- $this->safeDisconnect($this->db, $mainConnName);
- }
- }
- private function validateConnection($connection)
- {
- try {
- $pdo = $connection->getPdo();
- $stmt = $pdo->prepare("SELECT 1 AS connection_test");
- $stmt->execute();
- } catch (\Throwable $e) {
- $this->error = "数据库连接验证失败: " . $e->getMessage();
- }
- }
- /**
- * 手动关闭连接(定时任务必须调用)
- */
- public function close()
- {
- $this->safeDisconnect($this->db, $this->connName);
- }
- private function safeDisconnect(&$connection, $name)
- {
- try {
- if ($connection instanceof \Illuminate\Database\Connection) {
- // 断开物理连接
- $connection->disconnect();
- // 清除 Laravel 连接池
- DB::purge($name);
- // 移除配置
- Config::offsetUnset("database.connections.{$name}");
- // 引用置空
- $connection = null;
- }
- } catch (\Throwable $e) {
- // 忽略
- }
- }
- /**
- * 阻止依赖 __destruct
- */
- public function __destruct()
- {
- // 不做任何事,避免不确定行为
- }
- }
|