记录一下pusher实时推送消息
一.注册pusher
官网:https://pusher.com/
注册成功新建一个应用获取key,密匙,app_id
二.配置pusher
1.安装pusher
composer require pusher/pusher-php-server
2.配置config/broadcasting.php
'default' => env('BROADCAST_DRIVER', 'pusher'),
....
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => 'ap1',
'encrypted' => true,
/***
1.pusher使用curl向https://pusher.com提交数据,所以你需要配置证书;否则提交会失败
2.如果不配置证书,则需要设置curl的CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST
***/
'curl_options' => [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
]
],
],
.....
3.配置.env
BROADCAST_DRIVER=pusher
...
QUEUE_DRIVER=sync
/***
注意这块必须配置为sync
如果 QUEUE_DRIVER 配置是 redis 那么当触发事件的时候不会调用 Illuminate\Broadcasting\BroadcastManager 下的 createPusherDriver 方法。
也就是不生成 pusher 类发送事件
pusher 调试控制台不会收到事件通知
***/
...
PUSHER_APP_ID=xxx
PUSHER_APP_KEY=xxx
PUSHER_APP_SECRET=xxx
PUSHER_APP_CLUSTER=xxx
三.建立事件
1.创建事件类
php artisan make:event PusherEvent
2.简单修改一下
<?php
namespace App\Events;
use Event;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PusherEvent extends Event implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $info;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($info)
{
$this->info = $info;
}
/**
* 指定广播频道(对应前端的频道)
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return ['my-channel'];
}
/**
* 指定广播事件(对应前端的事件)
* @return string
*/
public function broadcastAs()
{
return 'my-event';
}
/**
* 获取广播数据,默认是广播的public属性的数据
*/
public function broadcastWith()
{
return ['info' => $this->info];
}
}
四.触发事件
两种方式:
1.控制器触发:
use Event;
//测试Pusher
public function testpusher(){
Event::fire(new \App\Events\PusherEvent('啦啦啦'));
return 'This is a Laravel Pusher Bridge Test!'.date("Y-m-d H:i:s");
}
2.创建一个 artisan 命令来触发事件.
php artisan make:command PusherEventCommand
打开命令类 app/Console/Commands/PusherEventCommand.php 编辑
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class PusherEventCommand extends Command
{
protected $signature = 'pusher:test {message}';
protected $description = 'pusher test';
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
event(new \App\Events\PusherEvent($this->argument('message')));
}
}
打开 app/Console/Kernel.php, 将刚创建的命令类添加至 $commands
protected $commands = [
\App\Console\Commands\PusherEventCommand::class,
];
配置完成之后 我们就可以通过 artisan 命令向 pusher 服务器发送事件
php artisan pusher:test "lalala"
结果如下: