【问题标题】:Laravel Event Broadcast not work with pusherLaravel 事件广播不适用于推送器
【发布时间】:2016-10-17 15:57:13
【问题描述】:
我在我的项目中使用了 pusher。我根据 laravel 文档配置广播。当我解雇我的事件推送器时,它对我不起作用。但是当我从推送器控制台发送数据时,推送器会接收到这些数据。
我也尝试过vinkla/pusher。它工作正常,但 laravel 事件广播不起作用。
请帮我。
这是我的TestEvent.php 代码
namespace Factum\Events;
use Factum\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class TestEvent implements ShouldBroadcast
{
use SerializesModels;
public $text;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($text)
{
$this->text = $text;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return ['test-channel'];
}
}
【问题讨论】:
标签:
laravel
events
pusher
broadcasting
【解决方案1】:
我遇到了类似的问题,并逐步解决了这些问题。
我假设你正在运行 Laravel 5.3。
下面是一步一步的演练,可能会有所帮助:
-
检查您的配置文件。在config\broadcasting.php:
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_ID'),
'options' => [
'cluster' => 'eu',
'encrypted' => true,
// 'host' => 'api-eu.pusher.com'
// 'debug' => true,
],
],
],
-
在您的 web.php 文件中创建测试路径:
Route::get('/broadcast', function() {
event(new \Factum\Events\TestEvent('Sent from my Laravel application'));
return 'ok';
});
-
在您的 TestEvent.php 事件文件中,您应该添加此方法以指定您的事件名称:
/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastAs()
{
return 'my_event';
}
-
打开您的Pusher dashboard 并转到调试控制台。
保持页面打开,这样您就可以注意到您是否收到了来自您的应用程序的成功请求。
-
启动或重新启动您的队列工作者。这一步可以成就或破坏一切。如果您将 Mysql 表用于队列,我将假设您已经设置了队列所需的“jobs”和“failed_jobs”数据库表。
另一个重要的元素是工作者——队列处理器。
如果没有活动的工作人员运行来处理您的队列,则作业 (TestEvent) 将“保留”在作业表中,这意味着作业处于挂起状态,并且在活动工作人员开始处理队列之前不会再发生任何事情。
你可以这样启动worker:
www@yourmachine# PHP artisan queue:work --tries=3
-
现在您已经准备好在“http://your-app.laravel/broadcast”上进行调用并检查您的推送器调试控制台以获取响应。
可选步骤:
如果仍然缺少某些东西,您可以像这样调试您的应用与 Pusher 的交互:
在您的测试路线中尝试这样做:
Route::get('/broadcast', function() {
// New Pusher instance with our config data
$pusher = new \Pusher(
config('broadcasting.connections.pusher.key'),
config('broadcasting.connections.pusher.secret'),
config('broadcasting.connections.pusher.app_id'),
config('broadcasting.connections.pusher.options')
);
// Enable pusher logging - I used an anonymous class and the Monolog
$pusher->set_logger(new class {
public function log($msg)
{
\Log::info($msg);
}
});
// Your data that you would like to send to Pusher
$data = ['text' => 'hello world from Laravel 5.3'];
// Sending the data to channel: "test_channel" with "my_event" event
$pusher->trigger( 'test_channel', 'my_event', $data);
return 'ok';
});
我希望它也对你有用!
祝您编码愉快! ;)
【解决方案2】:
1/ 你应该清除缓存
php artisan config:cache
php artisan config:clear
php artisan route:cache
php artisan route:clear
php artisan optimize --force
2/ 试试这个推送消息
2.1/ 包括:use Pusher\Laravel\Facades\Pusher;
2.2/ 内部路由添加:
Pusher::trigger('adevChannel', 'EventAdev', ['message' => $message]);
或
event(EventAdev($message) );