使用Laravel Echo的16个简单步骤

5e7d755b4d9ae817

先飚几句英文,说说 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

1585280191698069

// 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,网站跑起来了

1585280214140035

使用 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 class="row justify-content-center">
            <div>
                <div class="card card-default">
                    <div>Example Component</div>
                    <div>
                        <ul>
                            <li v-for="name in names" :key="name">{{ name }}</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
    export default {
        data () {
            return {
                names: []
            }
        },
        mounted() {
            let that = this
            // 12. 创建 Echo 监听
            Echo.channel('rss')
                .listen('RssCreatedEvent', (e) => {
                    that.names.push(e.name)
                });
        }
    }
</script>

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

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

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

<?php
namespace App\Events;
use Carbon\Carbon;
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 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 \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        // 14. 创建频道
        return new Channel('rss');
    }
    /**
     * 指定广播数据。
     *
     * @return array
     */
    public function broadcastWith()
    {
        // 返回当前时间
        return ['name' => Carbon::now()->toDateTimeString()];
    }
}

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

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

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

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
    </head>
    <body>
    <div id="app">
        <example-component></example-component>
    </div>
    <script src="{{ asset('js/app.js') }}"></script>
    </body>
</html>

注:需要在 header 引入

<meta name="csrf-token" content="{{ csrf_token() }}">

编译前端:

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

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

1585280296163968

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

总结

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

1.laradock 的使用

2.laravel echo server 的使用

3.广播事件

4.event() 辅助函数

5.$schedule 定时任务

6.Laravel Echo 的使用

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容