首页 > 解决方案 > 通过 Redis 在多个服务器上的 Laravel 事件监听器

问题描述

我将我的 Laravel 项目部署在多台服务器上,我的平衡器在它们之间分配访问者。

我想通过 Redis(队列)组织广播事件并在所有服务器上监听事件(服务器有一个公共的 redis 数据库)。

我有事件类:

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class BaseRedisEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public string $connection = 'redis';
    public string $queue = 'default';
    public string $channel = 'default';

    public function broadcastOn(): Channel
    {
        return new Channel($this->channel);
    }
}

和类监听器

use App\Events\Bitcoin\Address\CreatedEvent;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class BaseRedisListener
{
    public function __construct()
    {
    }

    public function handle(BaseRedisEvent $event)
    {
        Log::debug('New Event in Redis ' . var_export($event, true));
    }
}

发送事件后,我希望监听器在所有服务器上工作。

BaseRedisEvent::dispatch();

仅为发送事件的服务器将条目添加到日志中。我想要所有服务器。你能帮助我吗?

标签: laraveleventsredislistener

解决方案


无法登录文件。您应该使用添加自定义驱动程序来处理 /config/logging.php 中的日志。请记住,您应该为此实现自定义类。一些示例和教程https://cylab.be/blog/144/laravel-custom-logging

请谷歌有关 laravel 自定义日志驱动程序。


推荐阅读