laravel5.8+redis+laravel-echo广播系统

1,我们先用一个新项目做一个demo

通过 Composer 创建项目
 

composer create-project --prefer-dist laravel/laravel demo"5.8.*"

2.安装nodejs,版本不能太高否则编译会报错,还得降低版本,所以先安装一个低版本的nodejs

PS D:\phpstudy_pro\WWW\echo.test.com\demo> node -v
v15.13.0
PS D:\phpstudy_pro\WWW\echo.test.com\demo>

3全局安装laravel-echo-server   

 npm install -g laravel-echo-server

PS D:\phpstudy_pro\WWW\echo.test.com\demo> npm install -g laravel-echo-server
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.      
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

changed 203 packages, and audited 204 packages in 12s

16 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

4.初始化larvel-echo-server,生成配置文件

laravel-echo-server init

默认回车即可,

(第4个记得修改成自己的访问域名地址

PS D:\phpstudy_pro\WWW\echo.test.com\demo> laravel-echo-server init
//开发模式
? Do you want to run this server in development mode? Yes
//端口
? Which port would you like to serve from? 6001
//redis
? Which database would you like to use to store presence channel members? redis
//自己的域名
? Enter the host of your Laravel authentication server. http://echo.test.com/
//http
? Will you be serving on http or https? http
? Do you want to generate a client ID/Key for HTTP API? No
? Do you want to setup cross domain access to the API? No
? What do you want this config to be saved as? laravel-echo-server.json
Configuration file saved. Run laravel-echo-server start to run server.
PS D:\phpstudy_pro\WWW\echo.test.com\demo>

5.启动laravel-echo-server服务

laravel-echo-server start

PS D:\phpstudy_pro\WWW\echo.test.com\demo> laravel-echo-server start

L A R A V E L  E C H O  S E R V E R

version 1.6.3

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
[ioredis] Unhandled error event: ReplyError: NOAUTH Authentication required.
    at parseError (C:\Users\admin-1\AppData\Roaming\npm\node_modules\laravel-echo-server\node_modules\redis-parser\lib\parser.js:179:12)
    at parseType (C:\Users\admin-1\AppData\Roaming\npm\node_modules\laravel-echo-server\node_modules\redis-parser\lib\parser.js:302:14)
✔  Listening for redis events...
node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Redis could not subscribe.".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
PS D:\phpstudy_pro\WWW\echo.test.com\demo> 

报错

.env 配置文件增加  redis的地址密码端口

LARAVEL_ECHO_SERVER_REDIS_HOST=127.0.0.1
LARAVEL_ECHO_SERVER_REDIS_PASSWORD=123456
LARAVEL_ECHO_SERVER_REDIS_PORT=6379

重新执行

PS D:\phpstudy_pro\WWW\echo.test.com\demo> laravel-echo-server start

L A R A V E L  E C H O  S E R V E R

version 1.6.3

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

这些配置也需要改

    BROADCAST_DRIVER=redis
     
    QUEUE_CONNECTION=redis
     
     
    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=123456
    REDIS_PORT=6379

6. 开启一个新的命令窗口,

安装 Socket.io 客户端和 Laravel-Echo 包,在这之前建议运行一下 npm install 

npm install laravel-echo 

PS D:\phpstudy_pro\WWW\echo.test.com\demo>  npm install laravel-echo

up to date, audited 1178 packages in 5s

84 packages are looking for funding
  run `npm fund` for details

34 vulnerabilities (1 low, 10 moderate, 23 high)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
PS D:\phpstudy_pro\WWW\echo.test.com\demo> 

npm install --save socket.io-client 

PS D:\phpstudy_pro\WWW\echo.test.com\demo> npm install --save socket.io-client

added 13 packages, and audited 1193 packages in 15s

84 packages are looking for funding
  run `npm fund` for details

34 vulnerabilities (1 low, 10 moderate, 23 high)

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.
PS D:\phpstudy_pro\WWW\echo.test.com\demo> 

7.安装Predis库

D:\phpstudy_pro\WWW\echo.test.com\demo>composer require predis/predis
./composer.json has been updated
Running composer update predis/predis
Loading composer repositories with package information
Updating dependencies
Lock file operations: 1 install, 0 updates, 0 removals
  - Locking predis/predis (v2.1.1)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing predis/predis (v2.1.1): Extracting archive
Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
Package symfony/debug is abandoned, you should avoid using it. Use symfony/error-handler instead.
Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: beyondcode/laravel-dump-server
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
56 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
Found 3 security vulnerability advisories affecting 1 package.
Run composer audit for a full list of advisories.
Using version ^2.1 for predis/predis

8. config/app.php 中providers数组下解除注释
App\Providers\BroadcastServiceProvider::class

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,

9.不使用前缀名 database.php  修改   或者把前缀加入频道

    'redis' => [

        'client' => env('REDIS_CLIENT', 'predis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'predis'),
            // 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

10.创建事件类 并且 继承于 ShouldBroadcast 接口

文件地址位于 app/Events/..

php artisan make:event ExampleEvent 


PS D:\phpstudy_pro\WWW\echo.test.com\demo> php artisan make:event ExampleEvent
Event created successfully.
PS D:\phpstudy_pro\WWW\echo.test.com\demo>

 

<?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 ExampleEvent 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()
    {
        return new Channel('user1');
        //return new PrivateChannel('channel-name');
    }


    /**
 * 指定广播数据。
 *
 * @return array
 */
public function broadcastWith()
{
    return [
        'data' => '返回数据'
    ];
}


}

11 在控制器或者路由中用队列的方式调用该事件,我是先放在默认的welcome首页的路由中测试的。



Route::get('/', function () {
    broadcast(new \App\Events\ExampleEvent);
    return view('welcome');
});

12 开启队列 新开启一个命令窗口

 php artisan queue:work   后队列一个逻辑,(记得加入后台运行)


PS D:\phpstudy_pro\WWW\echo.test.com\demo> php artisan queue:work


13.前端监听 在resource/js/bootstrap.js中

import Echo from 'laravel-echo';
window.Echo = new Echo({
    broadcaster: 'socket.io',
    // 6001时在laravel-echo初始化时设置的端口
    host: window.location.hostname + ':6001',
    // 可以自定义传给授权接口的header信息
    auth: {headers: {Authorization: ''},},
});

14 welcome.blade.php页面中,也就是我们需要用到的广播页面中添加

//head 中加入令牌
<meta name="csrf-token" content="{{ csrf_token() }}">

    // 引入app.js
    <script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="js/app.js"></script>

 
// 监听并输出
<script>
 
//  ’user1'是频道,‘ExampleEvent’ 是监听的事件(这是事件的类名,你也可以根据你的需要自定义)
    window.Echo.channel('user1')
        .listen('ExampleEvent', (e) => {
            console.log(e);
        });
</script>
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>

                        @if (Route::has('register'))
                            <a href="{{ route('register') }}">Register</a>
                        @endif
                    @endauth
                </div>
            @endif

            <div class="content">
                <div class="title m-b-md">
                    Laravel
                </div>

                <div class="links">
                    <a href="https://laravel.com/docs">Docs</a>
                    <a href="https://laracasts.com">Laracasts</a>
                    <a href="https://laravel-news.com">News</a>
                    <a href="https://blog.laravel.com">Blog</a>
                    <a href="https://nova.laravel.com">Nova</a>
                    <a href="https://forge.laravel.com">Forge</a>
                    <a href="https://github.com/laravel/laravel">GitHub</a>
                </div>
            </div>
        </div>
    </body>
    // 引入app.js
    <script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="js/app.js"></script>

 
// 监听并输出
<script>
 
//  ’user1'是频道,‘ExampleEvent’ 是监听的事件(这是事件的类名,你也可以根据你的需要自定义)
    window.Echo.channel('user1')
        .listen('ExampleEvent', (e) => {
            console.log(e);
        });
</script>

</html>

在resource/js/app.js中 默认已引入

require('./bootstrap');

15.打包js   npm run dev

PS D:\phpstudy_pro\WWW\echo.test.com\demo> npm run dev

> dev
> npm run development


> development
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

        Additional dependencies must be installed. This will only take a moment.
 
        Running: npm install vue-template-compiler --save-dev --production=false
 
        Okay, done. The following packages have been installed and saved to your package.json dependencies list:
 
        - vue-template-compiler
 
98% after emitting SizeLimitsPlugin

 DONE  Compiled successfully in 6238ms                                                                                                                                                               下午5:33:12

       Asset      Size   Chunks             Chunk Names
/css/app.css   179 KiB  /js/app  [emitted]  /js/app
  /js/app.js  1.52 MiB  /js/app  [emitted]  /js/app
PS D:\phpstudy_pro\WWW\echo.test.com\demo> 

最后进入首页

 

 如果出现

Vue 报错 [Vue warn]: Cannot find element: #App ?

注释掉最后

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

// const app = new Vue({
//     el: '#app',
// });

 重新编译

npm run dev

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值