U8DatabaseServerService.php 2.5 KB

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