【问题标题】:Laravel multi-tenant jobsLaravel 多租户作业
【发布时间】:2017-06-19 20:39:48
【问题描述】:

遇到作业无法连接到数据库的问题。

Invalid catalog name: 1046 No database selected

我需要在作业中设置帐户,因此我有一个扩展类来确保帐户与作业一起发送,以便我可以确保数据库可以连接到正确的数据库。

<?php

namespace App\Jobs;

use Illuminate\Support\Facades\DB;

abstract class Job
{
    protected $account;

    public function start()
    {
        // runs when creating the job, so the config holds the correct value
        $this->account = config('database.connections.tenant.database');
    }

    public function handle()
    {
        // since the handle function runs outside of setting the job 
        // the database is no longer set in the config
        config()->set('database.connections.tenant.database', $this->account);
        // try to force it to reconnect incase it already did for some reason.
        DB::reconnect();
    }
}

这是我正在玩的当前版本,变化似乎不影响它。我基本上在构造函数中运行start,然后确保它在作业中运行父handle,以便引导正确的数据库配置。

我正在寻找的最终结果是将租户数据库设置为account,并在运行作业时使用该数据库进行所有查询。

【问题讨论】:

    标签: php laravel laravel-5 multi-tenant


    【解决方案1】:

    找到了解决这个问题的方法。它不漂亮,但根据我所看到的 laravel 队列并不能很好地处理这类事情。

    首先我删除了 handle 函数的覆盖,我真正需要的是确保运行队列所需的帐户在 Job 类上可用。

    abstract class Job
    {
        protected $account;
    
        public function start()
        {
            // runs when creating the job, so the config holds the correct value
            $this->account = config('database.connections.tenant.database');
        }
    }
    

    接下来,我在boot 方法中将切换到正确租户数据库的开关移至AppServiceProvider

    Event::listen(JobProcessing::class, function ($event) {
       if ($payload = $event->job->payload()) {
          preg_match('/"account";s:[0-9]+:"(.*?)"/', $payload['data']['command'], $matches);
          if (count($matches)) {
             if (isset($matches[1])) {
                config()->set('database.connections.tenant.database', $matches[1]);
                config()->set('database.default', 'tenant');
             }
          }
       }
    });
    

    我在这里所做的是使用一些正则表达式查看帐户的序列化对象。可能会在这里进行改进,但到目前为止在测试中有效。一旦确认帐户,它就会设置正确的数据库。

    我不得不走这么远的原因是,当作业本身被序列化时,作业会进行查询,因此为了传递帐户,它需要在序列化之前完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2015-10-04
      • 2023-01-25
      相关资源
      最近更新 更多