-
创建laravel项目(8.5.18)
composer create-project --prefer-dist laravel/laravel 项目名(最新版) // 安装predis扩展 composer require predis/predis
-
配置修改
1)config\app.phpproviders中 App\Providers\BroadcastServiceProvider::class取消注释
2) env文件中修改
// 队列驱动 QUEUE_DRIVER=redis // 广播驱动 BROADCAST_DRIVER=redis // 队列连接方式 QUEUE_CONNECTION=redis // redis配置 REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379
3) config\database.php
// 修改 REDIS_CLIENT为predis redis => [ 'client' => env('REDIS_CLIENT', 'predis'), ..... ] // rediskey前缀移除 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
-
创建事件
php artisan make:event News<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class News implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public $message; /** * 创建一个新的事件实例 * * @return void */ // public $broadcastQueue = 'news_queue'; public function __construct($message) { $this->message = $message; } /** * 获取事件广播的频道. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('news'); // return new PrivateChannel('channel-name'); } /** * 获取广播数据 * * @return array */ public function broadcastWith(){ return ['message' => $this->message]; } }
-
配置routes\channels.php
Broadcast::channel('news',function () { return true; });
-
添加console/web路由 都可以
// routes/console.php Artisan::command('bignews', function () { broadcast(new \App\Events\News(date('Y-m-d h:i:s A').":a BIG NEWS!")); $this->comment("news sent"); })->describe('Send news'); // routes/web.php Route::get('/queue', function () { broadcast(new \App\Events\News(date('Y-m-d h:i:s A').":a BIG NEWS!")); });
-
后端查看是否调通
1) 项目根目录下执行 php artisan bignews 命令 2) 消费news_queue队列 php artisan queue:work --queue=news_queue 3)安装websocket服务端 npm install -g laravel-echo-server laravel-echo-server init //初始化websocket服务端 laravel-echo-server start //启动 (开启消费队列)
4) (停止消费队列)连接redis redis-cli -h 127.0.0.1 -p 6379 查看 keys *
-
安装websocket客户端
npm install --save socket.io-client //安装websocket客户端 npm install --save laravel-echo //安装websocket客户端封装laravel-echo
-
1)修改resources/js/app.js
import Echo from 'laravel-echo' window.io = require('socket.io-client'); window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001' });
2)修改 webpack.mix.js
(如果在项目根目录下没有 webpack.config.js 配置文件,你可以把它拷贝到根目录下,同时修改 package.json 里的npm脚本: cp node_modules/laravel-mix/setup/webpack.config.js ./)mix.js('resources/js/app.js', 'public/js') // 新增
package.json 如下
{ "private": true, "scripts": { "dev": "npm run development", "development": "mix", "watch": "mix watch", "watch-poll": "mix watch -- --watch-options-poll=1000", "hot": "mix watch --hot", "prod": "npm run production", "production": "mix --production" }, "devDependencies": { "axios": "^0.21", "laravel-mix": "^6.0.6", "lodash": "^4.17.19", "postcss": "^8.1.14" }, "dependencies": { "laravel-echo": "^1.10.0", "socket.io-client": "^4.1.2" } }
3)终端执行
npm run dev // 如遇到mix命令未发现 // 执行 npm install laravel-mix@latest (安装最新版) // 再次执行 npm run dev
mix命令未发现示例图
4)执行成功 生成如下文件 public/js/app.js9. public/js/app.js
创建 resources/views/broadcasting.blade.php 文件{{--头部加入--}} <meta name="csrf-token" content="{{ csrf_token() }}"> {{--引入app.js--}} <script src="js/app.js"></script> {{--监听并输出--}} <script> // news是频道 News是监听的事件名 window.channel('news').listen('.News', (e) => { console.log(e); }); </script>
-
route配置
Route::get('/welcome', function () { return view('broadcasting'); });
-
路由进入 验证是否成功接收到消息 http://127.0.0.1:8081/welcome
在终端执行 laravel-echo-server start //启动 laravel-echo-server 连接socket php artisan queue:work //消费队列 php artisan bigNews //发送广播
-
结果如图:
过程中如遇到 以上命令执行后,终端日志显示都正常,而发出消息后,浏览器只有轮询请求如
http://127.0.0.1:6001/socket.io/?EIO=3&transport=polling&t=Nc8cMGt 这种。 没有websocket的请求和message。可以将socket.io-client版本降级,这里是2.3.1版本。(原来默认安装的是4.1.2版本,一直无法收到请求,参考转载博文评论得知)
代码地址
https://github.com/liangshuyan/laravel8.5-redis.git
Laravel8.5 广播(redis驱动)
最新推荐文章于 2021-08-04 10:35:51 发布