我正在尝试使用Laravel作为后端API客户端和SPA前端创建实时通知系统,我正在使用React作为前端,但是对于下面的示例,我将使用我创建的简单Vue.Js和blade以获取工作示例。
总之,我有一个路由触发事件,这类似于以下示例:
它触发的事件将看起来像这样:
总之,我有一个路由触发事件,这类似于以下示例:
Route::get('fire', function () {
// this fires the event
$user = App\Models\User::find(1);
event(new App\Events\CampaignUploadedWithSuccess($user, 'testing a notification'));
return "event fired";
});
它触发的事件将看起来像这样:
<?php
namespace App\Events;
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 CampaignUploadedWithSuccess implements ShouldBroadcast
{
protected $user;
public $notification;
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @param $user
* @param $notification
*/
public function __construct($user, $notification)
{
$this->user = $user;
$this->notification = $notification;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return ['notifications-channel.' . $this->user->id];
}
}
我正在一个名为notification-channel.{userId}
的频道上广播。
然后,我有一个使用node运行的socket.js文件。
它看起来像这样:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('notifications-channel.1', function(err, count) {
});
redis.on('message', function(channel, message) {
console.log('Notification Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
使用node socket.js
运行服务器,触发事件会像下面这样实现我想要的效果:
太棒了!我正在向一个频道广播。
然而,现在我有一个名为test.blade的blade文件,它将引入Vue和Socket.io
它看起来像这样:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
</head>
<body>
<h1>Notifications</h1>
<ul>
<li v-repeat="notification: notifications">@{{ notifications }}</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script>
<script>
var socket = io('http://localhost:3000');
new Vue({
el: 'body',
data: {
notifications: []
},
ready: function() {
socket.on('notifications-channel.1', function(data) {
alert(data.notification);
});
}
});
</script>
</body>
</html>
这里的目标是在通知通道1广播数据时,触发消息警报。但是它并没有起作用。
所以我的问题是,如何使用socket.io、Laravel和Redis将广播发送到频道并从频道消费广播。
我对私有频道也有些不了解,不知道如何创建一个仅供一个用户使用的频道。文档很好,但没有提供实现此目的并使多个平台消耗通知的真实世界示例。