Laravel 使用 laravel-echo 和 pusher-js 实现 WebSocket 广播
后端配置使用
1、安裝擴展包:
composer require beyondcode/laravel-websockets2、發布擴展包配置文件及遷移文件
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"3、運行數據庫遷移文件
php artisan migrate4、發布 laravel-websockets 配置文件、
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"5、安裝 pusher 的 php 擴展包 (laravel-websockets 的 api 完全兼容 pusher, 這里需要安裝)
composer require pusher/pusher-php-server "~3.0"6、修改.env 文件中廣播程序的驅動為 pusher
BROADCAST_DRIVER=pusher7、設置 config/broadcasting.php 中 pusher 配置
默認情況下,Laravel 應用程序廣播到 WebSocket 服務器時,是將事件信息發送到官方 Pusher 服務器。但是由于
Laravel WebSockets 包附帶了自己的 Pusher API 實現,因此我們需要告訴 Laravel
將事件發送到我們自己的服務器。
8、配置 websockets 應用 config/websockets.php
一般情況下默認即可
9、開啟 websocket 服務
php artisan websockets:serve --port=3300110、開啟隊列監聽
php artisan queue:listen --tries=511、將上邊兩個使用supervisor進程守護
12、設置nginx反向代理以啟用wss
server {listen 80;listen 443 ssl http2;#SSL-START SSL相關配置,請勿刪除或修改下一行帶注釋的404規則ssl_certificate fullchain.pem;ssl_certificate_key privkey.pem;ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;add_header Strict-Transport-Security "max-age=31536000";error_page 497 https://$host$request_uri;#SSL-END# https 下的 wss 反向代理location /wss/{proxy_pass http://127.0.0.1:33001/;#當前服務器的IPproxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header X-Real-IP $remote_addr;}***** }13、生成Event
php artisan make:event OrderNotifyEvent14、修改剛剛生成的Event文件,在app/Events目錄下
<?phpnamespace App\Events;use App\Models\Order; use Illuminate\Broadcasting\Channel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast;class OrderNotifyEvent implements ShouldBroadcast {/*** @var Order*/private $order;/*** Create a new event instance.** @param int $order_id*/public function __construct(int $order_id){$order = Order::with('hospital', 'take_delivery', 'goods_order_details.goods')->find($order_id);$this->order = $order;}/*** Get the channels the event should broadcast on.** @return \Illuminate\Broadcasting\Channel|array*/public function broadcastOn(){return new Channel('order-notify');}/*** 觸發事件時返回的數據** @return null|array*/public function broadcastWith(): ?array{return !is_null($this->order) ? $this->order->toArray() : [];} }15、在需要推送廣播的地方調用
broadcast(new \App\Events\OrderNotifyEvent(850));至此,后端完成
前端配置使用
1、安裝 laravel-echo 和 pusher-js 依賴
npm install laravel-echo npm install pusher-js2、新建 laravel-echo.js 文件
import Echo from 'laravel-echo'; import Pusher from 'pusher-js';/*** pusher配置*/ const pusherConfig = {id: 'mall_pusher',key: '1e47c980dd2c0eb78b79d03dce5c8dc5',secret: '008f442bd9cd15b20a07f31d4d3b2ae7',wsHost: window.location.hostname,wsPort: 33001,wsPath: null,wssPort: 443,cluster: 'mt1',forceTLS: location.protocol === 'https:',broadcaster: 'pusher',disableStats: true,enabledTransports: ['ws', 'wss'], }if (pusherConfig.forceTLS) {pusherConfig.wsPath = '/wss'; }class LaravelEcho {static instance = null;constructor() {this.instance = new Echo({client: new Pusher(pusherConfig.key, pusherConfig),broadcaster: pusherConfig.broadcaster})}setToken(token) {this.instance.options.client.config.auth.headers.Authorization = `Bearer ${token}`}removeToken() {this.instance.options.client.config.auth.headers = {}} }export default new LaravelEcho();3、在需要使用的地方引入
import LaravelEcho from '../utils/laravel-echo';LaravelEcho.instance.channel('order-notify').listen('OrderNotifyEvent', (e) => {if (!e || !e.id) {return;}const h = this.$createElement;const notify = this.$notify({title: '有新訂單',message: h('div', [h('span', `訂單編號:${e.order_no},`),h('a', {attrs: {href: 'javascript:void(0);',},style: {color: '#F54B64',},}, '點擊查看'),]),duration: 0,onClick: () => {this.order = Object.assign({}, this.order, e);this.modal.order_notify.show = true;notify.close();},});});總結
以上是生活随笔為你收集整理的Laravel 使用 laravel-echo 和 pusher-js 实现 WebSocket 广播的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上计算机课睡觉检讨书400,课堂上睡觉检
- 下一篇: R pdf大小_全能格式转换工具分享,P