aws lambda使用_如何使用AWS Lambda构建无服务器的Laravel队列

aws lambda使用

先决条件 (Prerequisites)

快速步骤 (Quick Steps)

  1. Install bref

    安装bref

  2. Deploy to AWS Lambda using serverless

    使用无服务器部署到AWS Lambda

  3. Configure Laravel queue to use SQS

    配置Laravel队列以使用SQS

  4. Bonus!

    奖金!

步骤1:安装bref (Step 1: Install bref)

Installing bref into existing Laravel application is quite simple, since it provides Laravel’s package already:

bref安装到现有的Laravel应用程序中非常简单,因为它已经提供了Laravel的软件包

$ composer require bref/bref bref/laravel-bridge

Then create aserverless.yml configuration file:

然后创建一个serverless.yml配置文件:

$ php artisan vendor:publish --tag=serverless-config

It will bring the default configuration that require to modify a bit to handle Laravel queue jobs as the following example:

它将带来默认配置,该配置需要修改一点以处理Laravel队列作业,如以下示例所示:

service: your-laravel-app-nameprovider:
name: aws
# The AWS region in which to deploy (us-east-1 is the default)
region: us-east-1
runtime: provided
# The stage of the application, e.g. dev, prod, staging
stage: prod
environment:
APP_ENV: production
SQS_QUEUE:
Ref: YourQueueName
iamRoleStatements:
# Allows our code to interact with SQS
- Effect: Allow
Action: [sqs:SendMessage, sqs:DeleteMessage]
Resource:
Fn::GetAtt: [ YourQueueName, Arn ]functions:
worker:
handler: worker.php
timeout: 900 # in seconds
layers:
- ${bref:layer.php-74}
events:
- sqs:
arn:
Fn::GetAtt: [ YourQueueName, Arn ]
# Only 1 item at a time to simplify error handling
batchSize: 1package:
exclude:
- .env
- node_modules/**
- public/storage
- resources/assets/**
- storage/**
- tests/**plugins:
- ./vendor/bref/brefresources:
Resources:
# The queue
YourQueueName:
Type: AWS::SQS::Queue
Properties:
VisibilityTimeout: 900
RedrivePolicy:
maxReceiveCount: 3 # jobs will be retried up to 3 times
# Failed jobs (after the retries) will be moved to the other queue for storage
deadLetterTargetArn:
Fn::GetAtt: [ YourQueueFailedName, Arn ]# Failed jobs will go into that SQS queue to be stored, until a developer looks at these errors
YourQueueFailedName:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600 # maximum retention: 14 days

On the part of configuration code above, you will notice worker.php which is used to handle SQS events in AWS Lambda, then just create it on your Laravel project folder:

在上面的配置代码中,您会注意到worker.php用来处理AWS Lambda中的SQS事件,然后在Laravel项目文件夹中创建它:

<?php declare(strict_types=1);use Bref\LaravelBridge\Queue\LaravelSqsHandler;
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->makeWith(LaravelSqsHandler::class, [
'connection' => 'sqs', // this is the Laravel Queue connection
'queue' => getenv('SQS_QUEUE'),
]);

步骤2:使用无服务器部署到AWS Lambda (Step 2: Deploy to AWS Lambda using serverless)

The magic will be done by serverless in just few commands and it will setup all for you. Install it by using npm or yarn:

神奇的事情将由无服务器执行 ,只需几个命令,它将为您完成所有设置。 使用npmyarn安装它

$ npm install -g serverless
# or
$ yarn global add serverless

Once installed if you haven’t setup aws configure command before, you need to create AWS access keys and configure it by the following a command:

如果之前没有设置过aws configure命令,则安装后,需要创建AWS访问密钥并通过以下命令对其进行配置:

$ serverless config credentials --provider aws --key <key> --secret <secret>

In somehow I faced an error of “AWS provider credentials not found …” when run it on my root of Laravel’s project folder, and get fixed by running on the outside of the folder, very strange!

在我的Laravel项目文件夹的根目录上运行它时,以某种方式我遇到了“ 找不到AWS提供程序凭证... ”的错误,并通过在该文件夹的外部运行而得到修复,这很奇怪!

Deploy the Laravel application on your AWS account by running:

通过运行以下命令在您的AWS账户上部署Laravel应用程序:

$ serverless deploy

If you are lucky then you won’t see any error and shows the lambda’s function name instead.

如果幸运的话,您将不会看到任何错误,而是显示lambda的函数名称。

步骤3:将Laravel队列配置为使用SQS (Step 3: Configure Laravel queue to use SQS)

If the serverless’s deployment is going well, it will generate 2 SQS queues on your AWS account that you need to take a look for the main queue’s name to put it on .env as SQS_QUEUE, thus you need to update .env file accordingly and also switch the use SQS connection:

如果无服务器的部署进展顺利,它会生成2个SQS队列您的AWS帐号,你需要看一看主队列的名字把它放在.envSQS_QUEUE ,因此你需要更新.env相应文件并切换使用SQS连接:

# .env
QUEUE_CONNECTION=sqs
SQS_PREFIX=https://sqs.us-east-1.amazonaws.com/<your-account-id>
SQS_QUEUE=<generated-queue-name-from-aws>
AWS_ACCESS_KEY_ID=<key>
AWS_SECRET_ACCESS_KEY=<secret>
AWS_DEFAULT_REGION=us-east-1

Add a token config to config/queue.php :

token配置添加到config/queue.php

'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),'token' => env('AWS_SESSION_TOKEN'),
...

Finally, you can dispatch the job as general Laravel job, for example:

最后,您可以将作业调度为常规Laravel作业,例如:

ProcessPodcast::dispatch($podcastId);

步骤4:加分! (Step 4: Bonus!)

In real world implementation, we had some issues! Here are some tips and tricks to handle them:

在现实世界中,我们遇到了一些问题! 这里有一些技巧和窍门来处理它们:

  • Debugging is important!bref is really awesome, it ships with nice dashboard to see any things from the AWS Lambda’s logs locally by running:

    调试很重要! bref真的很棒,它带有漂亮的仪表板,可通过运行以下命令在本地查看AWS Lambda日志中的所有内容:

$ vendor/bin/bref dashboard
# or with console view
$ serverless logs -f <generated-lambda-function-name> --tail
  • My lambda has no internet access!Don’t worry it is not end of the world :) I was surprise also on the first time. Basically, you need to create a NAT Gateway in the VPC that Lambda uses. This tutorial shows how to do.

    我的lambda无法访问互联网! 不用担心这不是世界末日:)第一次我也感到惊讶。 基本上,您需要在Lambda使用的VPC中创建NAT网关。 本教程显示了如何做。

  • Connect to AWS RDSIn my case I use RDS for the database, all you need is by using same Security Group between RDS instance and Lambda function. See more details from bref’s docs.

    连接到AWS RDS就我而言,我将RDS用于数据库,您所需要的只是在RDS实例和Lambda函数之间使用相同的安全组查看 bref文档的更多详细信息。

  • Don’t expose secret variables!You might store API tokens, password etc at serverless.yml file which is required to be committed into your git repo. A best approach is by using SSM parameter store, follow from bref’s official docs for more details.

    不要公开秘密变量! 您可以将API令牌,密码等存储在serverless.yml文件中,该文件需要提交到git repo中。 最好的方法是使用SSM参数存储库 ,有关详细信息,请参考bref的官方文档

翻译自: https://medium.com/@agungdarmanto/how-to-build-a-serverless-laravel-queue-using-aws-lambda-2cd74f9113c2

aws lambda使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值