agrodata/laravel-echo-api-gateway 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

agrodata/laravel-echo-api-gateway

Composer 安装命令:

composer require agrodata/laravel-echo-api-gateway

包简介

Use Laravel Echo with API Gateway Websockets

README 文档

README

CI codecov

This package enables you to use API Gateway‘s Websockets as a driver for Laravel Echo , so you don’t have to use services like Pusher or Socket.io.

It works by setting up a websocket API in API Gateway, and configure it to invoke a Lambda function, every time a message is sent to the websocket. This package includes and autoconfigures a handler to respond to these websocket messages. We also configure Laravel to use this connection as a broadcast driver.

This package currently only works with either Bref or Laravel Vapor, though the latter one involves some manual set-up.

Requirements

In order to use this package, your project needs to meet the following criteria:

  • PHP 8.x
  • Laravel 6 to 12
  • Uses either bref or Laravel Vapor to deploy to AWS
  • Has a working queue
  • Uses Laravel Mix or any other tool to bundle your assets

Installation

Installation of this package is fairly simply.

First we have to install both the composer and npm package:

composer require georgeboot/laravel-echo-api-gateway

yarn add laravel-echo-api-gateway
# or
npm install --save-dev laravel-echo-api-gateway

Platform-specific instructions

A. When using Bref

Next, when using Bref, we have to add some elements to our serverless.yml file. If using Vapor, these resources have to be created by hand using the AWS CLI or console.

Add a new function that will handle websocket events (messages etc):

functions:
    # Add this function
    websocket:
        handler: handlers/websocket.php
        layers:
            - ${bref:layer.php-80}
        events:
            - websocket: $disconnect
            - websocket: $default

Add a resource to create and configure our DynamoDB table, where connections will be stored in:

resources:
    Resources:
        # Add this resource
        ConnectionsTable:
            Type: AWS::DynamoDB::Table
            Properties:
                TableName: connections
                AttributeDefinitions:
                    - AttributeName: connectionId
                      AttributeType: S
                    - AttributeName: channel
                      AttributeType: S
                KeySchema:
                    - AttributeName: connectionId
                      KeyType: HASH
                    - AttributeName: channel
                      KeyType: RANGE
                GlobalSecondaryIndexes:
                    - IndexName: lookup-by-channel
                      KeySchema:
                          - AttributeName: channel
                            KeyType: HASH
                      Projection:
                          ProjectionType: ALL
                    - IndexName: lookup-by-connection
                      KeySchema:
                          - AttributeName: connectionId
                            KeyType: HASH
                      Projection:
                          ProjectionType: ALL
                BillingMode: PAY_PER_REQUEST

Add the following iamRoleStatement to enable our Lambda function to access the table:

provider:
    name: aws

    iamRoleStatements:
        # Add this iamRoleStatement
        - Effect: Allow
          Action: [ dynamodb:Query, dynamodb:GetItem, dynamodb:PutItem, dynamodb:UpdateItem, dynamodb:DeleteItem, dynamodb:BatchWriteItem ]
          Resource:
              - !GetAtt ConnectionsTable.Arn
              - !Join [ '', [ !GetAtt ConnectionsTable.Arn, '/index/*' ] ]

Add an environment variable to autogenerate our websocket URL:

provider:
    name: aws

    environment:
        # Add these variables
        # Please note : in Laravel 11, this setting is now BROADCAST_CONNECTION
        BROADCAST_DRIVER: laravel-echo-api-gateway
        LARAVEL_ECHO_API_GATEWAY_DYNAMODB_TABLE: !Ref ConnectionsTable
        LARAVEL_ECHO_API_GATEWAY_API_ID: !Ref WebsocketsApi
        LARAVEL_ECHO_API_GATEWAY_API_STAGE: "${self:provider.stage}"

Next, create the PHP handler file in handlers/websocket.php

<?php

use Georgeboot\LaravelEchoApiGateway\Handler;
use Illuminate\Foundation\Application;

require __DIR__ . '/../vendor/autoload.php';

/** @var Application $app */
$app = require __DIR__ . '/../bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

return $app->make(Handler::class);

Now, deploy your app by running serverless deploy or similar. Write down the websocket url the output gives you.

B. When using Vapor

When using Vapor, you will have to create these required resources by hand using the AWS CLI or Console:

B1. DynamoDB table for connections

Create a DynamoDB table for the connections. Use connectionId (string) as a HASH key, and channel (string) as a SORT key. Set the capacity setting to whatever you like (probably on-demand).

Create 2 indexes:

  1. Name: lookup-by-connection, key: connectionId, no sort key, projected: ALL
  2. Name: lookup-by-channel, key: channel, no sort key, projected: ALL
B2. API Gateway

Create a new Websocket API. Enter a name and leave the route selection expression to what it is. Add a $disconnect and $default. Set both integrations to Lambda and select your CLI lambda from the list. Set the name of the stage to what you desire and create the API. Once created, write down the ID, as we'll need it later.

B3. IAM Permissions

In IAM, go to roles and open laravel-vapor-role. Open the inline policy and edit it. On the JSON tab, add "execute-api:*" to the list of actions.

Then, login to Laravel Vapor, go to team settings, AWS Accounts, click on Role next to the correct account and deselect Receive Updates.

Edit your .env:

BROADCAST_DRIVER=laravel-echo-api-gateway
LARAVEL_ECHO_API_GATEWAY_DYNAMODB_TABLE=the-table-name-you-entered-when-creating-it
LARAVEL_ECHO_API_GATEWAY_API_ID=your-websocket-api-id
LARAVEL_ECHO_API_GATEWAY_API_STAGE=your-api-stage-name

Generate front-end code

Add to your javascript file:

import Echo from 'laravel-echo';
import {broadcaster} from 'laravel-echo-api-gateway';

window.Echo = new Echo({
    broadcaster,
    // replace the placeholders
    host: 'wss://{api-ip}.execute-api.{region}.amazonaws.com/{stage}',
    authEndpoint: '{auth-url}/broadcasting/auth', // Optional: Use if you have a separate authentication endpoint
    bearerToken: '{token}', // Optional: Use if you need a Bearer Token for authentication
});

You can also enable console output by passing a debug: true otpion to your window.Echo intializer :

import Echo from 'laravel-echo';
import {broadcaster} from 'laravel-echo-api-gateway';

window.Echo = new Echo({
    broadcaster,
    // replace the placeholders
    host: 'wss://{api-ip}.execute-api.{region}.amazonaws.com/{stage}',
    debug: true
});

Lastly, you have to generate your assets by running Laravel Mix. After this step, you should be up and running.

agrodata/laravel-echo-api-gateway 适用场景与选型建议

agrodata/laravel-echo-api-gateway 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.7k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 04 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「WebSockets」 「laravel」 「echo」 「serverless」 「bref」 「laravel vapor」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 agrodata/laravel-echo-api-gateway 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 agrodata/laravel-echo-api-gateway 我们能提供哪些服务?
定制开发 / 二次开发

基于 agrodata/laravel-echo-api-gateway 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.7k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 24
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-04-09