Home > PHP Framework > Laravel > body text

Let's talk about the broadcast mechanism of laravel7.0, there is always what you want!

藏色散人
Release: 2021-07-29 09:01:47
forward
1869 people have browsed it

laravel7.0 broadcast mechanism (Redis socket.io)

Broadcast service provider

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"

Setting up Redis connection

Need to modify the broadcast driver in the .env file to redis:

BROADCAST_DRIVER=redis
Copy after login

Create Event

php artisan make:event OrderShipped
Copy after login

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 &#39;anyName&#39;;
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel(&#39;orderStatus&#39;);
    }
}
Copy after login

Set api routing

Route::get(&#39;/ship&#39;, function (Request $request) {
    $id = $request->input(&#39;id&#39;);
    broadcast(new OrderShipped($id)); // 触发事件
    return &#39;Order Shipped!&#39;;
});
Copy after login

Install front-end scaffolding

composer require laravel/uiphp artisan ui vue --auth
Copy after login

Redis

Because we use Redis broadcast , you need to install the Predis library:

composer require predis/predis
Copy after login

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

Install laravel-echo-server and subscribe to Redis Sub

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
Copy after login

Initialize 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)
Copy after login

Start laravel-echo-server

laravel-echo-server start
Copy after login
  • After successful startup, it will Output the following log
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!
Copy after login

Test broadcast

Execute on the browserhttp://yourhost/api/ship?id=16

Channel: laravel_database_orderStatus
Event: anyName
Copy after login
  • laravel-echo-server Connection successful!

Install the pre-dependency of laravel-echo

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
Copy after login
in
package.json

Edit resource/js/bootstrap.js and add the following code

import Echo from "laravel-echo";
window.io = require("socket.io-client");
window.Echo = new Echo({    
broadcaster: "socket.io",    
host: window.location.hostname + ":6001"
});
Copy after login

测试页面

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>
Copy after login

js 代码的意思是收听 news 通道内的 News 事件对象,将接收到的事件在控制台打印出来。

基本构建

npm install && npm run watch
Copy after login

相关推荐:最新的五个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!

Related labels:
source:任志帆的博客
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template