devig/laravel-google-pubsub-broadcaster

使用 Laravel 向 Google PubSub 广播事件

dev-master 2022-03-11 19:29 UTC

This package is not auto-updated.

Last update: 2024-09-22 05:33:29 UTC


README

使用 Laravel 轻松向 Google Pub/Sub 广播事件。

安装

$ composer require whatdafox/laravel-google-pubsub-broadcaster

Laravel 会自动检测服务提供者。

用法

更新您的 .env 文件

BROADCAST_DRIVER=google-pubsub
GOOGLE_CLOUD_PROJECT=dev-moment-244207
GOOGLE_APPLICATION_CREDENTIALS=gcloud.json

创建事件并启用广播

<?php

namespace App\Events;

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

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

    public $someData;

    /**
     * Create a new event instance.
     *
     * @param $someData
     */
    public function __construct($someData)
    {
        $this->someData = $someData;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('your-channel-name');
    }
}

订阅

将很快推出一个用于订阅主题的软件包。在此期间,您可以使用 Google PubSub PHP 库,例如

<?php

namespace App\Console\Commands;

use Illuminate\Broadcasting\Channel;
use Illuminate\Console\Command;
use Google\Cloud\PubSub\PubSubClient;

class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pubsub:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Subscribe to a Google PubSub channel';

    /**
     * Execute the console command.
     *
     * @param PubSubClient $client
     * @return mixed
     */
    public function handle(PubSubClient $client)
    {
        $topic = $client->topic('channel-name');
        
        if(!$topic->exists()) {
            $topic->create();
        }
        
        $subscription = $topic->subscription('subscriber-name');

        if(!$subscription->exists()) {
            $subscription->create();
        }

        while(true) {
            $messages = $subscription->pull([
                'returnImmediately' => true,
                'maxMessages' => 5,
            ]);

            if(empty($messages)) {
                continue;
            }

            foreach ($messages as $message) {
                
                // Do something with the message
                
                $subscription->acknowledge($message);
            }
        }
    }
}