TPlusDatabaseServerService.php 2.4 KB

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