目录php
本教程会详细介绍配置的方法,以给全体用户发送通知为例。css
文件位置 config/broadcasting.php前端
<?php return [ 'default' => env('BROADCAST_DRIVER', 'null'), 'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ // ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ];
能够看到Laravel自带了4个广播驱动器 pusher, redis, log, nullvue
服务提供器位置:App\Providers\BroadcastServiceProvidernode
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Broadcast; class BroadcastServiceProvider extends ServiceProvider { public function boot() { Broadcast::routes(); require base_path('routes/channels.php'); } }
你只需在 config/app.php 配置文件的 providers 数组中取消对该提供者的注释便可webpack
这里采用 redis + soocket.io 的组合laravel
若是你使用 Redis 广播器,请安装 Predis 库:git
composer require predis/predis "~1.0"
这里采用社区驱动维护的项目 tlaverdure/laravel-echo-server,这是一个使用socket.io来支持laravel广播的nodejs服务器。当运行后会将socket.io客户端js代码暴露在一个标准的的url中。咱们须要在咱们的项目中(视图文件)引入这个地址。github
npm install -g laravel-echo-server # 这里是全局安装
我是这样选择初始化配置的。能够根据本身状况改变web
$ laravel-echo-server init ? Do you want to run this server in development mode? Yes ? Which port would you like to serve from? 6001 ? Which database would you like to use to store presence channel members? redis ? Enter the host of your Laravel authentication server. archerwong.cn ? Will you be serving on http or https? http ? Do you want to generate a client ID/Key for HTTP API? Yes ? Do you want to setup cross domain access to the API? No appId: c953434932b06864 key: 551440289d2d41c81e87d55c1d0217e5 Configuration file saved. Run laravel-echo-server start to run server.
$ laravel-echo-server start L A R A V E L E C H O S E R V E R version 1.3.6 ⚠ Starting server in DEV mode... ✔ Running at localhost on port 6001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready!
检测下socket.io客户端url地址是否可访问
http://your_host_address:6001/socket.io/socket.io.js
可访问,并内容相似于如下则说明服务器可用
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(......
Laravel Echo 是一个 JavaScript 库,它使得订阅频道和监听由 Laravel 广播的事件变得很是容易。
npm install laravel-echo --save # 安装laravel-echo 并记录package.json
官方说法是在resources/assets/js/bootstrap.js文件底部引入是个好地方,打开该文件加入下面内容
import Echo from "laravel-echo" window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
其实若是使用blade模板,没有使用vue等前端,咱们须要在入口视图定义id="app"挂载点,不然打包后会发现#app未定义,而且会打包进去vue等咱们不须要的内容,文件也会变大,
简单粗暴一点能够修改resource/assets/js/app.js,直接打包咱们须要的内容
import Echo from "laravel-echo" window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
修改 webpack.mix.js
let mix = require('laravel-mix'); mix.js('resources/assets/js/app.js', 'public/js'); // .sass('resources/assets/sass/app.scss', 'public/css');
生成
npm run dev
这样咱们就获得了一个压缩的public/app.js文件
Laravel Echo 会须要访问当前会话的 CSRF 令牌,能够在应用程序的 head HTML 元素中定义一个 meta 标签:
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="/js/app.js"></script> <script> <!--上面app.js已经进行了Echo的实例化,而后应该使用实例化的Echo进行广播事件的监听--> console.log(Echo); </script>
到此为止,咱们基本的配置已经完成,Echo的前端监听等后面讲到再补充。
修改.env 中的配置
QUEUE_DRIVER=redis
运行队列监听
php artisan queue:work
建立文件 app/Events/TestBroadcastingEvent.php, 内容以下
<?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; use App\Http\Model\Notice; class TestBroadcastingEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public $notice; /** * Create a new event instance. * * @return void */ public function __construct(Notice $notice) { $this->notice = $notice; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('notice'); } }
<?php namespace App\Http\Controllers\Home; use App\Http\Model\Notice; use App\Events\TestBroadcastingEvent; class TestController extends CommonController { public function send($id) { //当须要给全体发通知的时候触发 $notice = Notice::find($id); event(new TestBroadcastingEvent($notice)); } }
应该还记得前面已经实例化了Echo,如今就是要用这个Echo进行监听,实现广播功能
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script> <script src="/js/app.js"></script> <script> <!--上面app.js已经进行了Echo的实例化,而后应该使用实例化的Echo进行广播事件的监听--> console.log(Echo); Echo.channel('notice') .listen('TestBroadcastingEvent', (e) => { // 若是有广播过来你能够进行逻辑操做,好比给用户一个通知 console.log(e); console.log(e.order); });
触发send()方法进行测试,控制台输出以下内容
{notice: {…}, socket: null} {id: 1, content: "感谢你的仔细阅读,期待共同进步!", created_at: null, updated_at: null}
发现咱们后端TestBroadcastingEvent事件类的notice属性被传递过来了,你就能够收到个人感谢了。
后端: laravel-echo-server服务器 (经过url地址暴露 socket.io.js)=> 编写并触发广播事件
前端: laravel-echo库 + 后端暴露的socket.io.js => 实例化Echo => 监听广播事件