先飚几句英文,说说 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 服务端)。

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

今天利用最简便的「16」步,走一遍代码集成 laradocklaravel-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

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

使用 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 class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        <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

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

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

总结

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

  1. laradock 的使用
  2. laravel echo server 的使用
  3. 广播事件
  4. event() 辅助函数
  5. $schedule 定时任务
  6. Laravel Echo 的使用

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

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

「完」

Copyright © coding01 2017 all right reserved,powered by Gitbook该文件修订时间: 2018-06-17 22:20:20

results matching ""

    No results matching ""