聊聊laravel7.0的廣播機制,總有你想要的!

laravel7.0廣播機制(redis + socket.io)

廣播服務提供者

在廣播任意事件之前,首先需要注冊appprovidersbroadcastserviceprovider。在新安裝的 laravel 應用中,你只需要取消 config/app.php 配置文件中 providers 數組內對應服務提供者之前的注釋即可。該提供者允許你注冊廣播授權路由和回調

相關欄目教程推薦:《laravel教程

設置 Redis 連接

需要修改 .env 文件中的廣播驅動為 redis:

BROADCAST_DRIVER=redis

建立 Event

php?artisan?make:event?OrderShipped

執行上訴命令之后 app 目錄下會出現一個 Events 目錄,在該目錄下產生了廣播事件類 OrderShipped.php。我們要對自動生成的 OrderShipped 類進行以下修改

  • 增加對 ShouldBroadcast 的實現

  • 修改 broadcastOn 方法,使用公共廣播通道 orderStatus

  • 自定義廣播的消息名(非必須)【默認情況下,Laravel 會使用事件的類名來廣播事件,不過,你可以通過在事件中定義 broadcastAs 方法來自定義廣播名稱:】

  • 修改構造函數

完整修改如下 可直接替換

<?php namespace AppEvents; use IlluminateBroadcastingChannel; use IlluminateBroadcastingInteractsWithSockets; use IlluminateBroadcastingPresenceChannel; use IlluminateBroadcastingPrivateChannel; use IlluminateContractsBroadcastingShouldBroadcast; use IlluminateFoundationEventsDispatchable; use IlluminateQueueSerializesModels; 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?IlluminateBroadcastingChannel|array ?????*/ ????public?function?broadcastOn() ????{ ????????return?new?Channel('orderStatus'); ????} }

設置 api 路由

Route::get('/ship',?function?(Request?$request)?{ ????$id?=?$request-&gt;input('id'); ????broadcast(new?OrderShipped($id));?//?觸發事件 ????return?'Order?Shipped!'; });

安裝前端腳手架

composer?require?laravel/uiphp?artisan?ui?vue?--auth

Redis

因為咱們使用 Redis 廣播,需要安裝 Predis 庫:

composer?require?predis/predis

Redis 廣播使用 Redis 的 pub/sub 功能進行廣播;不過,你需要將其和能夠接受 Redis 消息的 websocket 服務器進行配對以便將消息廣播到 Websocket 頻道

當 Redis 廣播發布事件時,事件將會被發布到指定的頻道上,傳遞的數據是一個 JSON 格式的字符串,其中包含了事件名稱、負載數據 data、以及生成事件 socket ID 的用戶

安裝 laravel-echo-server 訂閱 Redis Sub

如果使用 pusher 那么直接使只用 laravel 就可以了,如果使用 Redis + socket.io 則需要使用開源項目 laravel教程 。所以我們現在要使用 laravel-echo-server

全局安裝

npm?install?-g?laravel-echo-server

初始化 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

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!

測試廣播

在瀏覽器上執行 http://yourhost/api/ship?id=16

Channel:?laravel_database_orderStatus Event:?anyName
  • laravel-echo-server 連接成功!

安裝 laravel-echo 的前依賴

由于前端使用的是 laravel-echo來收聽廣播,我們選擇的底層實現方式是socket.io。所以首先我們要在package.json中添加 laravel-echo 和 socket.io的依賴

npm?i?--save?socket.io-client npm?i?--save?laravel-echo

編輯 Resource/js/bootstrap.js 添加如下代碼

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 內容為

nbsp;html&gt;    ????<meta> ????<meta> ????<meta> ????<meta> ????<title>News?Room</title> ????<link> ????<div> ????????News?Room ????</div> ????<script></script> ????<script>         Echo.channel("laravel_database_orderStatus") // 廣播頻道名稱     .listen(".anyName", e => {         // 消息名稱         console.log(e); // 收到消息進行的操作,參數 e 為所攜帶的數據     });     </script>

js 代碼的意思是收聽 news 通道內的 News 事件對象,將接收到的事件在控制臺打印出來。

基本構建

npm?install?&amp;&amp;?npm?run?watch

相關推薦:laravel教程

? 版權聲明
THE END
喜歡就支持一下吧
點贊12 分享