简单16步搞定Laravel Echo的使用

简单16步搞定Laravel Echo的使用

先飚几句英文,说说 laravel echo 的作用:

One of my favorite projects in the laravel ecosystem is Echo. Echo enables real-time web applications through the use of websockets and hooks directly into Laravel’s Event broadcasting features. this means developers can use a familiar php API to send real-time data. A very common use-case for this type of functionality would be a notification or chat system.翻译「略」摘自:https://www.imarc.com/blog/realtime-notifications-with-laravel-echo-server-docker-and-traefik

官方文档推荐使用 Pusher 或者 laravel-echo-server (是一个使用 NodeJS + Socket.IO 实现的 WebSocket 服务端)。

推荐:laravel教程

在国内,个人还是不推荐使用 Pusher,访问速度有所影响,而且其还是一个商业产品。

今天利用最简便的「16」步,走一遍代码集成 laradock 和 laravel-echo-server 来使用 Laravel Echo。

搭建基础环境

// 1. new project laravel new echolearning // 2. 使用 laradock git clone https://github.com/Laradock/laradock.git // 3. 创建 .env cp env-example .env // 4. 创建 container docker-compose up -d php-worker laravel-echo-server nginx redis

简单16步搞定Laravel Echo的使用

// 5. 进入 workspace 容器 docker-compose exec --user=laradock workspace bash // 6. 安装插件 // 6.1 推荐使用 laravel-china 维护的 composer 国内镜像 composer config -g repo.packagist composer https://packagist.laravel-china.org // 6.2 并行下载插件 composer global require "hirak/prestissimo" // 6.3 配置 yarn 国内镜像 yarn config set registry 'https://registry.npm.taobao.org' // 注:以上可以在 laradock 中配置 // 6.4 执行安装 composer install yarn install // 7. 创建 .env 和 key cp .env.example .env php artisan key:generate

好了,我们开始在浏览器输入:http://localhost,网站跑起来了

简单16步搞定Laravel Echo的使用

使用 Laravel Echo Server

因为 laradock 集成了「Laravel Echo Server」,所以我们很方便的使用到 Laravel Echo。

// 8. 配置广播驱动和 redis 服务器 BROADCAST_DRIVER=redis REDIS_HOST=redis // 9. 安装 predis composer require predis/predis

准备好后端配置后,我们开始安装前端插件,毕竟 Laravel Echo 是前端工具。

// 10. 安装 socket.io-client laravel-echo yarn add socket.io-client laravel-echo

在 resources/assets/js/bootstrap.js 实例化 Echo:

// 11. 实例化 Echo import Echo from 'laravel-echo' window.io = require('socket.io-client') window.Echo = new Echo({     broadcaster: 'socket.io',     host: window.location.hostname + ':6001' }); // Laravel 官方推荐使用 pusher // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ //     broadcaster: 'pusher', //     key: process.env.MIX_PUSHER_APP_KEY, //     cluster: process.env.MIX_PUSHER_APP_CLUSTER, //     encrypted: true // });

接下来我们就可以使用 Echo 实例,监听后端发过来的广播或者通知了。

首先我们利用已经给的 ExampleComponent 改造下,创建 Echo 监听,等待数据的到来,然后再显示在页面上。代码简单:

<template>     <div>         <div>             <div>                 <div>                     <div>Example Component</div>                     <div>                         <ul>                             <li>{{ name }}</li>                         </ul>                     </div>                 </div>             </div>         </div>     </div> </template><script>     export default {         data () {             return {                 names: []             }         },         mounted() {             let that = this             // 12. 创建 Echo 监听             Echo.channel(&#39;rss&#39;)                 .listen(&#39;RssCreatedEvent&#39;, (e) => {                     that.names.push(e.name)                 });         }     } </script>

我们在后端添加一个 rss 被创建的事件 RssCreatedEvent,并继承 ShouldBroadcast。

// 13. 创建 RssCreatedEvent 事件 php artisan make:event RssCreatedEvent

我们使用假数据,让它返回当前的时间,方便查看效果:

<?php namespace AppEvents; use CarbonCarbon; use IlluminateBroadcastingChannel; use IlluminateQueueSerializesModels; use IlluminateBroadcastingPrivateChannel; use IlluminateBroadcastingPresenceChannel; use IlluminateFoundationEventsDispatchable; use IlluminateBroadcastingInteractsWithSockets; use IlluminateContractsBroadcastingShouldBroadcast; class RssCreatedEvent implements ShouldBroadcast {     use Dispatchable, InteractsWithSockets, SerializesModels;     /**      * Create a new event instance.      *      * @return void      */     public function __construct()     {         //     }     /**      * Get the channels the event should broadcast on.      *      * @return IlluminateBroadcastingChannel|array      */     public function broadcastOn()     {         // 14. 创建频道         return new Channel(&#39;rss&#39;);     }     /**      * 指定广播数据。      *      * @return array      */     public function broadcastWith()     {         // 返回当前时间         return [&#39;name&#39; => Carbon::now()-&gt;toDateTimeString()];     } }

然后我们就可以做一个定时任务了,让它每隔一分钟,广播一次:

protected function schedule(Schedule $schedule) {     // 15. 每隔一分钟执行一次     $schedule-&gt;call(function () {         event(new RssCreatedEvent());     })-&gt;everyMinute(); }

最后让首页加载 vue 组件,刷新测试:

nbsp;html&gt; getLocale() }}"&gt;              <meta>         <meta>         <meta>         <meta>         <title>Laravel</title>               <div>         <example-component></example-component>     </div>     <script></script>      

注:需要在 header 引入

<meta>

编译前端:

// 16. 运行 watch yarn run watch-poll

刷新网页,查看运行效果:

简单16步搞定Laravel Echo的使用

如我们所愿,每隔一分钟,广播一次,前端 laravel-echo 监听并捕获该广播,然后读取数据,展示出来。

总结

到目前为止,我们用到的技术都有:

1.laradock 的使用

2.laravel echo server 的使用

3.广播事件

4.event() 辅助函数

5.$schedule 定时任务

6.Laravel Echo 的使用

我们基本可以使用 Laravel Echo 了,至于更深入的使用,推荐查看官网文档。

最后再一次强烈推荐大家用 laradock 来部署 Docker 开发环境,因为你想要用到的工具和环境,相信 laradock 都为你准备好了。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享