U8DatabaseServerService.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Service;
  3. use Illuminate\Support\Facades\Config;
  4. use Illuminate\Support\Facades\DB;
  5. class U8DatabaseServerService extends Service
  6. {
  7. public $db = null;
  8. public $error = null; // 错误信息
  9. private $database = "";
  10. private $connName = "";
  11. public function __construct($loginUser = [])
  12. {
  13. $this->database = $loginUser['zt_database'] ?? "";
  14. $this->connName = 'sqlsrv_main_' . uniqid();
  15. $this->createConnection();
  16. }
  17. private function createConnection()
  18. {
  19. // 主数据库连接
  20. $mainConnName = $this->connName;
  21. $mainConfig = [
  22. 'driver' => 'sqlsrv',
  23. 'host' => env('SQLSRV_HOST'),
  24. 'port' => env('SQLSRV_PORT'),
  25. 'database' => $this->database,
  26. 'username' => env('SQLSRV_USERNAME'),
  27. 'password' => env('SQLSRV_PASSWORD'),
  28. 'options' => [
  29. \PDO::SQLSRV_ATTR_QUERY_TIMEOUT => 30, // SQL Server专用超时
  30. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  31. ],
  32. ];
  33. Config::set("database.connections.{$mainConnName}", $mainConfig);
  34. $this->db = DB::connection($mainConnName);
  35. // 测试连接有效性
  36. $this->validateConnection($this->db);
  37. }
  38. private function validateConnection($connection)
  39. {
  40. try {
  41. $pdo = $connection->getPdo();
  42. $stmt = $pdo->prepare("SELECT 1 AS connection_test");
  43. $stmt->execute();
  44. $result = $stmt->fetch(\PDO::FETCH_ASSOC);
  45. if (empty($result) || $result['connection_test'] != 1) {
  46. $this->error = "数据库连接失败";
  47. }
  48. } catch (\Throwable $e) {
  49. $this->error = "数据库连接验证失败: " . $e->getMessage();
  50. }
  51. }
  52. public function __destruct()
  53. {
  54. // 主动关闭连接
  55. $this->safeDisconnect($this->db);
  56. }
  57. private function safeDisconnect(&$connection)
  58. {
  59. try {
  60. if ($connection instanceof \Illuminate\Database\Connection) {
  61. // 物理断开连接
  62. $connection->disconnect();
  63. // 获取连接名称
  64. $name = $connection->getName();
  65. // 清除 Laravel 内置连接池
  66. DB::purge($name);
  67. // 移除动态配置
  68. Config::offsetUnset("database.connections.{$name}");
  69. // 清除连接引用
  70. $connection = null;
  71. // Log::info("动作", [
  72. // 'param' => "执行了析构",
  73. // ]);
  74. }
  75. } catch (\Throwable $e) {
  76. // 静默处理断开错误
  77. // Log::info("错误", [
  78. // 'param' => $e->getMessage(),
  79. // ]);
  80. }
  81. }
  82. }