whatdafox / laravel-google-pubsub-broadcaster
此包已被废弃且不再维护。未建议替代包。
使用Laravel向Google Pub/Sub广播事件
dev-master
2019-06-19 12:10 UTC
Requires
- php: >=7.3.0
- google/cloud-pubsub: ^1.13
- illuminate/broadcasting: ~5.7.0|~5.8.0
- illuminate/support: ~5.7.0|~5.8.0
This package is auto-updated.
Last update: 2023-02-20 06:42:23 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); } } } }