3

我在宅基地上使用 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;
        }

如果您能帮助我找出这种行为背后的原因以及如何让这一切实时发生,而不是现在存在的延迟,那将会很有帮助。

4

2 回答 2

2

您应该更改ShouldBroadcastShouldBroadcastNow. 这将解决延迟问题。

于 2020-11-20T10:07:27.030 回答
1

尝试这个:

将您的 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;
于 2017-01-26T17:21:00.913 回答