laravel7.0 broadcast mechanism (Redis socket.io)
Before broadcasting any event, you first need to registerApp\ Providers\BroadcastServiceProvider
. In the newly installed Laravel application, you only need to uncomment the corresponding service provider in the providers
array in the config/app.php
configuration file. This provider allows you to register broadcast authorization routes and callbacks
Related column tutorial recommendations: "laravel tutorial"
Need to modify the broadcast driver in the .env
file to redis
:
BROADCAST_DRIVER=redis
php artisan make:event OrderShipped
After executing the appeal command, an Events directory will appear in the app directory, and the broadcast event class OrderShipped.php
will be generated in this directory. We need to make the following modifications to the automatically generated OrderShipped class
Add the implementation of ShouldBroadcast
Modify the broadcastOn method and use the public broadcast channel orderStatus
Customize the broadcast message name (Not required) [By default, Laravel will use the class name of the event to broadcast the event, but you can pass it in the event Define the broadcastAs method in to customize the broadcast name:】
Modify the constructor
The complete modification is as follows and can be directly replaced
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class OrderShipped implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; //可添加任意成员变量 public $id; //事件构造函数 public function __construct($id) { $this->id = $id; } //自定义广播的消息名 public function broadcastAs() { return 'anyName'; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('orderStatus'); } }
Route::get('/ship', function (Request $request) { $id = $request->input('id'); broadcast(new OrderShipped($id)); // 触发事件 return 'Order Shipped!'; });
composer require laravel/uiphp artisan ui vue --auth
Because we use Redis broadcast , you need to install the Predis library:
composer require predis/predis
Redis broadcast uses the pub/sub function of Redis for broadcast; however, you need to combine it with the one that can accept Redis The Websocket server of the message is paired to broadcast the message to the Websocket channel
When Redis broadcasts an event, the event will be published to the specified channel, and the data passed is in a JSON format string, which contains the event name, load data data, and the user who generated the event socket ID
If you use pusher, then directly Just use laravel. If you use Redis socket.io, you need to use the open source project laravel-echo-server. So now we are going to use laravel-echo-server
Global installation
npm install -g laravel-echo-server
laravel-echo-server init // 是否在开发模式下运行此服务器(y/n) 输入y ? Do you want to run this server in development mode? (y/N)// 设置服务器的端口 默认 6001 输入 6001就可以了 或者你想要的 ? Which port would you like to serve from? (6001)// 想用的数据库 选择 redis ? Which database would you like to use to store presence channel members? (Use arrow keys)❯ redis sqlite // 这里输入 你的laravel 项目的访问域名 ? Enter the host of your Laravel authentication server. (http://localhost)// 选择 网络协议 http ? Will you be serving on http or https? (Use arrow keys)❯ http https // 您想为HTTP API生成客户端ID/密钥吗 N ? Do you want to generate a client ID/Key for HTTP API? (y/N)// 要设置对API的跨域访问吗?(y/n)N Configuration file saved. Run laravel-echo-server start to run server. //您希望将此配置另存为什么? (laravel-echo-server.json)回车就行 ? What do you want this config to be saved as? (laravel-echo-server.json)
laravel-echo-server start
L A R A V E L E C H O S E R V E R version 1.6.0 ⚠ Starting server in DEV mode... ✔ Running at localhost on port 6001 ✔ Channels are ready. ✔ Listening for http events... ✔ Listening for redis events... Server ready!
Execute on the browserhttp://yourhost/api/ship?id=16
Channel: laravel_database_orderStatus Event: anyName
Since the front-end uses laravel-echo
to listen to the broadcast, the underlying implementation we chose is socket.io
. So first we need to add laravel-echo
and socket.io
dependencies
npm i --save socket.io-client npm i --save laravel-echo
import Echo from "laravel-echo"; window.io = require("socket.io-client"); window.Echo = new Echo({ broadcaster: "socket.io", host: window.location.hostname + ":6001" });
在 resources/views/
下建立页面 test.blade.php 内容为
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content=""> <title>News Room</title> <link href="" rel="stylesheet"> </head> <body> <div class="content"> News Room </div> <script src=""></script> <script> Echo.channel("laravel_database_orderStatus") // 广播频道名称 .listen(".anyName", e => { // 消息名称 console.log(e); // 收到消息进行的操作,参数 e 为所携带的数据 }); </script> </body> </html>
js 代码的意思是收听 news 通道内的 News 事件对象,将接收到的事件在控制台打印出来。
npm install && npm run watch
相关推荐:最新的五个Laravel视频教程
The above is the detailed content of Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!. For more information, please follow other related articles on the PHP Chinese website!