【问题标题】:Tell Laravel to stop trying a connection after X seconds [duplicate]告诉 Laravel 在 X 秒后停止尝试连接 [重复]
【发布时间】:2021-05-08 12:19:54
【问题描述】:

我有一个使用两个数据库连接的 Laravel 应用程序。

始终可以访问一个(并且是我的环境中配置的默认设置)。

另一个是远程的,可能无法访问(这是它的预期行为)。

第二个数据库只能通过按钮访问。我希望仅当数据库可访问时才启用此按钮。

为此,我使用了一个简单的Livewire 组件来检查DB::('second_db')->getPdo();

这是我的组件

// blade
<button wire:init="loadDisabled" class="..." {{ $this->disabled ? 'disabled' : '' }}>
    Access DB
</button>

// Component class
public $disabled = true;

function loadDisabled()
{
   try {
       DB::connection('second_db')->getPdo();
   } catch (PDOException $e) {
       $this->disabled = true;
   }
   $this->disabled = false;
}

public function render()
{
   return view('livewire.my-component');
}

使用 Tinker 时,我在几秒钟后尝试了DB::connection('second_db')-&gt;getPdo();(我认为很多),我得到了PDOException with message 'SQLSTATE[HY000] [335544721] Unable to complete network request to host "...",因为数据库处于脱机状态(这是我所期望的)但是当我在网络上使用包含我的 livewire 组件的页面,我从nginx 得到了一个504 Gateway time-out

我什至尝试用catch(Exception $e) 捕捉任何异常,但同样的事情发生了

我深入挖掘并意识到这是由于默认的valet-linux 配置。

当我搜索解决方案时,每个人都建议增加超时时间,但我不想这样做!

我想告诉我的程序做什么:

  1. 尝试 X 秒(比如 5 秒甚至更短)以获取 pdo
  2. 如果可行,很好,给我真实的
  3. 如果没有,就抛出 PDOException(或任何更适合这种情况的 Exception)
  4. 让我处理 catch 块中的异常

基本上,我希望我的应用程序在触发nginx 错误之前“决定停止”,因为我知道如果需要那么长时间,那就是我的数据库无法访问,这就是我正在寻找的.

【问题讨论】:

  • 感谢您的评论。这很奇怪,我尝试了建议的解决方案,它有效......我删除了添加的代码,它仍然有效!

标签: php laravel nginx laravel-valet


【解决方案1】:

您可以进行并行处理。尝试使用 Laravel 队列并将结果传递给 Notification 实例,这将由您的按钮元素反映出来。可能需要 3-5 秒左右。

您也可以采用异步方式。 spatie/async 包可以帮助您并行运行代码,因此您可以连接到数据库并同时跟踪时间。如果时间过去了,你总是可以抛出异常。

使用 spatie/async 你的代码看起来更像这样:

$pool
->add(function () {
    // Attempt your database connection
})
->then(function ($output) {
    // when successful, update livewire component
})
->catch(function ($exception) {
    // if you have a custom timeout exception, here's the best place
})
->timeout(function () {
    // or you let the package handle the timeout, perform your timeout action here 
});

在此处了解更多信息:https://github.com/spatie/async#asynchronous-and-parallel-php

如果您想要更多本机控制,它可能会导致您进行一些严重的 PHP 代码操作,我建议您从这里开始:https://www.php.net/manual/en/function.set-time-limit.php#115057

【讨论】:

  • 感谢您的回答,我使用了 PHP 原生函数,它工作正常,我删除了它(出于调试目的)它仍然工作......奇怪
猜你喜欢
  • 2021-12-02
  • 2013-08-25
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 2012-07-14
  • 1970-01-01
相关资源
最近更新 更多