我在宅基地上使用Laravel 5.3。这是我用于通过pusher和laravel echo广播事件的代码,用于实时通知用户新消息 -
class NewMessageReceived implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $message;
public $user;
public $sender;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message, User $user)
{
$this->message = $message;
$this->user = $user;
$this->sender = \Auth::user();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('user.'. $this->user->id);
}
}
以下是调用此事件的代码 -
try{
$m = $privateChat->messages()->save($m);
if( isset(Auth::user()->guide))
event ( new NewMessageReceived( $m, $m->messageable->tourist->user ));
else
event ( new NewMessageReceived( $m, $m->messageable->guide->user ));
return $m;
}
catch(Exception $e){
return $e;
}
在vue中有一个ajax调用,它接收上面代码生成的响应,即$ m。
问题是如果我使用下面的代码而不是上面的代码,响应速度至少快5倍。我只需要删除事件触发部分以使其运行更快(这是不希望的,因为我想实时更新用户) -
try{
$m = $privateChat->messages()->save($m);
return $m;
}
catch(Exception $e){
return $e;
}
如果你能帮助我发现这种行为背后的原因以及如何实现这一切,而不是现在存在的延迟,那将会很有帮助。
答案 0 :(得分:0)
试试这个:
将if逻辑移至事件类
class NewMessageReceived implements ShouldBroadcast
{
use InteractsWithSockets, SerializesModels;
public $message;
public $user;
public $sender;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message)
{
$this->message = $message;
$this->user = isset(Auth::user()->guide)) ? $message->messageable->tourist->user : $this->user = $message->messageable->guide->user;
$this->sender = \Auth::user();
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('user.'. $this->user->id);
}
}
现在您的事件致电。
$m = $privateChat->messages()->save($m);
event(new NewMessageReceived($m));
return $m;
答案 1 :(得分:-1)
您应将format
更改为ShouldBroadcast
。这样可以延迟解决问题。