本篇大部分是借鉴alexxiyang 的优快云 博客 ,全文地址请点击:https://blog.youkuaiyun.com/nsrainbow/article/details/80428769?utm_source=copy
所以没有详细说明,只是增加了些实际的细节。
基本配置 redis需安装
.evn
设置广播驱动 BROADCAST_DRIVER=redis
广播机制是基于queue机制实现的 QUEUE_DRIVER=redis
config/app.php
建立广播服务, ‘provides’ 属性,将 BroadcastServiceProvider 前的注释去掉。查看redis event等相关项是否打开。
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
定义频道 routes/channels.php
频道为news,不管是谁都可以接收到广播
Broadcast::channel('news', function ($user, $id) {
return true;
});
以下命令建立广播事件类
php artisan make:event News
app 目录下多出来一个 Events目录,在该目录下产生了广播事件类 News.php。编辑如下:
class News implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($news_message)
{
$this->message = $news_message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('news');
}
}
方便测试,编辑 routes/console.php ,增加 bignews 命令:
//要引入News类
Artisan::command('bignews', function () {
broadcast(new News("BIG NEWS!"));
$this->comment("news sent");
})->describe('Send news');
如果按照以上配置,打开两个cmd命令窗口
一窗口
php artisan bignews
news sent
这是发现redis中有了一个queue对象,说明连接上了redis:
redis-cli
127.0.0.1:6379> keys *
1) "queues:default"
让Laravel Queue Worker消费Event
php artisan queue:work
[2018-09-23 13:00:42] Processing: App\Events\News
[2018-09-23 13:00:42] Processed: App\Events\News
queue worker的执行界面看到该Event已经被检测到,并通过Redis Sub/Pub机制传播出去了。
首先需要安装node。
打开node中文网 http://nodejs.cn/download/

下载之后上传到linux服务器,
tar -xvf解压
重命名
mv node-v10.8.0-linux-x64 nodejs
在nodejs/bin下
-rwxrwxr-x 1 500 500 38171296 Aug 2 00:08 node
lrwxrwxrwx 1 500 500 38 Aug 2 00:08 npm -> ../lib/node_modules/npm/bin/npm-cli.js
lrwxrwxrwx 1 500 500 38 Aug 2 00:08 npx -> ../lib/node_modules/npm/bin/npx-cli.js
把node,npm变为全局命令:
vim /etc/profile
//在文件结尾加上以下两行:
export NODE_HOME=/usr/nodejs //node文件夹路径
export PATH=$NODE_HOME/bin:$PATH
source /etc/profile //让配置立即生效
再运行
node -v
v10.8.0
npm -v
6.2.0
node安装完毕。接下来是比较繁琐的部分。
回到项目根目录。
查看是否安装了webpack及版本。
npm info webpack
如果没有安装,百度安装一个。
一般在项目根目录运行npm init会生成package.json文件,但是生成的试过屡屡不成功,可以创建这个文件,以我这个为参考。
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch-poll": "npm run watch -- --watch-poll",
"hot": "NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production",
"production": "NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"dependencies": {
"bootstrap-sass": "^3.3.7",
"jquery": "^3.3.1",
"laravel-echo": "^1.4.0",
"socket.io-client": "^2.1.1"
},
"devDependencies": {
"axios": "^0.17",
"laravel-mix": "^2.1.14",
"lodash": "^4.17.4",
"webpack": "^3.0.0"
}
}
接下来用扩展包laravel-echo-server运行websocket端(之后的操作都是在项目根目录):
安装laravel-echo-server:
npm install -g laravel-echo-server
初始化:laravel-echo-server init
laravel-echo-server init
? Do you want to run this server in development mode? No
? Which port would you like to serve from? 6001
? Which database would you like to use to store presence channel members? redis
? Enter the host of your Laravel authentication server. http://localhost
? 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
Configuration file saved. Run laravel-echo-server start to run server.
这时候会产生一个laravel-echo-server.json文件
vim laravel-echo-server.json
{
"authHost": "http://127.0.0.1",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": true, //这里改成true
"host": null,
"port": "6001",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": true,//这里改为true 允许跨域
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}
输入laravel会自动补全laravel-echo-serve
laravel-echo-serve start
L A R A V E L E C H O S E R V E R
version 1.4.2
⚠ Starting server in DEV mode...
✔ Running at localhost on port 6001
✔ Channels are ready.
✔ Listening for http events...
✔ Listening for redis events...
Server ready!
我们再回到第一个终端窗口,再次广播一个news Event。你会发现 laravel-echo-server 会输出以下日志
Channel: news
Event: App\Events\News
CHANNEL news
laravel-echo-server连接成功!
ctrl+c断开laravel-echo-server,接下来安装所必须的程序:
前端使用的是 laravel-echo来收听广播。我们选择的底层实现方式是socket.io所以首先我们要在package.json中添加 laravel-echo 和 socket.io的依赖.
npm i --save socket.io-client
npm i --save laravel-echo
(出现警告不用管)
安装laravel-mix:
npm install --save-dev laravel-mix
该安装的都安装完毕。下边都是容易报错的部分,执行
npm install --unsafe-perm=true --allow-root
没问题再运行以下命令来编译js,css文件:
npm run dev
DONE Compiled successfully in 1094ms 6:29:41 PM
Asset
Size Chunks Chunk Names
/js/app.js 1.16 MB 0 [emitted] [big] /js/app
/css/app.css 0 bytes 0 [emitted] /js/app
这两步如果没有报错,就成功大半了。
(难免会报错,调试过程中,每变动了package.json,需执行以下操作:
删除node_modules rm -rf node_modules
清除npm缓存 npm cache clean -f
然后重新npm install --unsafe-perm=true --allow-root)
接下来修改前端。
打开 /resources/assets/js/bootstrap.js 你会发现在这个文件的结尾已经预先写上了 laravel-echo 的使用例子。因为我们使用的是socket.io所以把原来的注释掉。
/*import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key',
cluster: 'mt1',
encrypted: true
});*/
import Echo from 'laravel-echo'
window.io = require('socket.io-client');
window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});
这样页面在初始化的时候就会连接上laravel-echo-server。
bootstrap.js 会被 resources/assets/js/app.js 调用。
修改要广播的页面:
<meta name="csrf-token" content="{{ csrf_token() }}"> //这个不能少
<link href="{{ mix('css/app.css') }}" rel="stylesheet">
<script src="{{ mix('js/app.js') }}"></script>
<script>
Echo.channel('news')
.listen('News', (e) => {
console.log(e.message);//调试
alert(e.message);//弹出
});
</script>
当然不能忽略的一点是,如果是阿里云的服务器,到阿里云开放6001端口,否则会跨域拒绝的情况。
测试:
运行laravel-echo-server start
运行 php artisan bignews
不同系统可能会出现不同的情况,有什么问题,请留言,尽力为大家解答。
本文详细介绍如何在Laravel项目中配置并使用广播功能,包括安装Redis、设置广播驱动、定义频道、创建广播事件类、配置laravel-echo-server、前端监听等步骤,最终实现通过WebSocket实时推送消息。
462

被折叠的 条评论
为什么被折叠?



