aws lambda使用_使用AWS Lambda安排Slack消息

aws lambda使用

Migrating to serverless brings a lot of questions. How do you do some of the non-serverless tasks, such as a cronjob in a serverless application?

迁移到无服务器带来了很多问题。 您如何执行一些非无服务器的任务,例如无服务器应用程序中的cronjob?

Let’s say you have a small Slack app that sends the top five stories from Hacker News to your Slack channel. At some point you decided to shut down the server where you run that app, but you still want to receive the stories. Serverless with AWS Lambda seems cool. But how do you trigger the AWS Lambda function at a specific time?

假设您有一个小型的Slack应用,可将Hacker News的前五个故事发送到您的Slack频道。 在某个时候,您决定关闭运行该应用程序的服务器,但是您仍然想接收这些故事。 带有AWS Lambda的无服务器似乎很棒。 但是,如何在特定时间触发AWS Lambda函数?

In case you’re not familiar, serverless is a method of deploying and running applications on cloud infrastructure, on a pay-per-use basis and without renting or buying servers. To learn more about serverless and how it works with AWS, see this guide.

如果您不熟悉,无服务器是一种在按需付费的基础上且无需租用或购买服务器的情况下,在云基础架构上部署和运行应用程序的方法。 要了解有关无服务器及其如何与AWS一起使用的更多信息,请参阅本指南

You can trigger AWS Lambda functions with a variety of AWS services, such as API Gateway for APIs and S3 for files. For the full list of services, see the docs here. One of the available triggers is AWS CloudWatch Events.

您可以使用各种AWS服务触发AWS Lambda函数,例如用于API的API网关和用于文件的S3。 有关服务的完整列表,请参见此处的文档。 可用的触发器之一是AWS CloudWatch Events

Wait, isn’t CloudWatch for logs?

等一下,CloudWatch是否没有日志?

Well, it is. But it seems someone at AWS is a big fan of Dr. Jekyll and Mr. Hyde and in some cases a few different services are hidden behind the same name (hello Cognito).

好吧,是的。 但是,似乎AWS的某个人是Jekyll博士和Hyde先生的忠实拥护者,并且在某些情况下,同一个名字后面隐藏着一些不同的服务(您好Cognito )。

Beside serving logs, Amazon CloudWatch has events that deliver a near real-time stream of system events that describe changes in AWS resources. Events can also schedule automated actions using cron or rate expressions. Bingo!

除了服务日志外,Amazon CloudWatch还具有事件,这些事件提供了几乎实时的系统事件流,这些流描述了AWS资源的变化。 事件还可以使用cron或rate表达式安排自动操作。 答对了!

申请流程 (Application flow)

How would the app work with CloudWatch Events?

该应用程序如何与CloudWatch Events一起使用?

You need to configure a CloudWatch scheduled event using cron syntax or rate expression (ie. 5 minutes). The CloudWatch event then triggers an AWS Lambda function at configured intervals. In your AWS Lambda function, you get the top five articles from the Hacker News API and post them to Slack using Incoming Webhooks.

您需要使用cron语法或速率表达式(即5分钟)配置CloudWatch计划的事件。 然后,CloudWatch事件以配置的时间间隔触发AWS Lambda函数。 在您的AWS Lambda函数中,您可以从Hacker News API中获取前五篇文章,然后使用Incoming Webhooks将它们发布到Slack。

You can see the flow in the figure below.

您可以在下图中看到流程。

This sounds simple, right? Let’s see how it works in practice.

这听起来很简单,对吧? 让我们看看它在实践中是如何工作的。

发送预定的消息 (Sending scheduled messages)

Before we begin, to be able to follow along with this tutorial, you need to have an AWS account, and AWS CLI and Node.js (v6+) need to be installed. You can get AWS CLI here.

在开始之前,为了能够跟随本教程的学习,您需要拥有一个AWS账户,并且需要安装AWS CLI和Node.js(v6 +)。 您可以在此处获取AWS CLI。

You’ll also need to configure a Slack Incoming Webhook. To do so, follow this tutorial. At the end of the tutorial, you’ll get the webhook URL. Save that URL, because you’ll need it in a short while. Go, do it, I’ll wait here ⏳

您还需要配置Slack传入Webhook。 为此,请遵循本教程 。 在本教程的最后,您将获得Webhook URL。 保存该URL,因为您很快就会需要它。 去吧,我在这里等

Ok, times up! Let’s start with the fun part.

好,时间到了! 让我们从有趣的部分开始。

To start, create a new folder and start a new Node.js project in it (you can use npm init -y command).

首先,创建一个新文件夹并在其中启动一个新的Node.js项目(可以使用npm init -y命令)。

As, you’ll need to send a few HTTP requests, install the minimal request promise module from NPM as a dependency. To do so, run the following command:

同样,您将需要发送一些HTTP请求,并从NPM安装最小请求承诺模块作为依赖项。 为此,请运行以下命令:

npm install minimal-request-promise --save

Minimal request promise is a small Node.js module that simply wraps native HTTP and HTTPS modules into JavaScript Promises.

最小的请求承诺是一个小的Node.js模块,它仅将本机HTTP和HTTPS模块包装到JavaScript Promises中。

Now that the dependency is ready, let’s take a look at the next figure with the project structure that you we will use.

现在已经准备好依赖项,让我们看一下下图以及将要使用的项目结构。

Even through the code is simple, we’ll split it into few small files to simplify the testing (see the intro to hexagonal architecture for more info). As you can see in the figure above, your code contains following files:

即使代码很简单,我们也将其分成几个小文件以简化测试(有关详细信息,请参见六角形架构简介 )。 如上图所示,您的代码包含以下文件:

  • index.js - the initial file for your Lambda function that invokes the other two files and responds back to CloudWatch Events.

    index.js -Lambda函数的初始文件,该函数调用其他两个文件并响应CloudWatch Events。

  • src/get-top-hackernews-stories.js - a file that gets five top stories with details from Hacker News.

    src/get-top-hackernews-stories.js一个文件,该文件从Hacker News获取五个带有详细信息src/get-top-hackernews-stories.js新闻。

  • src/send-slack-message.js - a file that formats and sends a Slack message.

    src/send-slack-message.js格式化并发送Slack消息的文件。

Let’s start with the initial file. This file just requires the other two files and invokes the getTopHackerNewsStories and then the sendSlackMessage function. When both functions are ready, or if an error occurs, it responds back to the trigger (CloudWatch Event).

让我们从初始文件开始。 该文件仅需要其他两个文件,并先调用getTopHackerNewsStories ,然后调用sendSlackMessage函数。 当两个功能都准备就绪或发生错误时,它会响应触发器(CloudWatch Event)。

Your index.js file should look like the following code listing.

您的index.js文件应类似于以下代码清单。

For readability, it doesn't contain event validation, which should be present in production code.

为了便于阅读,它不包含事件验证,而事件验证应该出现在生产代码中。

'use strict'
const getTopHackerNewsStories = require('./src/get-top-hackernews-stories')
const sendSlackMessage = require('./src/send-slack-message')
function scheduledSlackMessage(event, context, callback) {  getTopHackerNewsStories()    .then(stories => sendSlackMessage(stories))    .then(() => callback(null))    .catch(callback)}
exports.handler = scheduledSlackMessage

The first of the two functions, getTopHackerNewsStories, makes an HTTP request to Hacker News API (no authentication required). As the API returns a list of story IDs, you need to get the first five IDs and send an HTTP request for each ID, to get the story’s details. Finally, you need to parse the response body (because the minimal request promise is not doing that under the hood) and return the results.

这两个函数中的第一个, getTopHackerNewsStories ,向Hacker News API发出HTTP请求(无需身份验证)。 当API返回故事ID的列表时,您需要获取前五个ID,并为每个ID发送一个HTTP请求,以获取故事的详细信息。 最后,您需要解析响应主体(因为最小请求承诺不会在后台执行)并返回结果。

Your get-top-hackernews-stories.js file should look like the next code listing.

您的get-top-hackernews-stories.js文件应类似于下一个代码清单。

'use strict'
const rp = require('minimal-request-promise')
function getTopNews() {  return rp.get('https://hacker-news.firebaseio.com/v0/topstories.json', {    'Content-Type': 'application/json'  })    .then(response => {      const storyIds = JSON.parse(response.body)
return Promise.all(        storyIds.slice(0, 5)          .map(id => {            return rp.get(`https://hacker-news.firebaseio.com/v0/item/${id}.json`, {              'Content-Type': 'application/json'            })              .then(response => JSON.parse(response.body))          })      )    })}
module.exports = getTopNews

When you get the stories, the sendSlackMessage function formats the message and sends another HTTP request to the Slack Incoming Webhook URL, as shown in the following code listing.

当您得到这些故事时, sendSlackMessage函数将格式化消息并向Slack传入Webhook URL发送另一个HTTP请求,如以下代码清单所示。

Instead of hardcoding the Incoming Webhook URL, we will pass it as an AWS Lambda environment variable. To learn more about environment variables and other ways of sharing secrets in serverless apps, see this guide.

与其对输入的Webhook URL进行硬编码,我们将其作为AWS Lambda环境变量进行传递。 要了解有关环境变量以及在无服务器应用程序中共享机密的其他方式的更多信息,请参阅本指南

'use strict'
const rp = require('minimal-request-promise')
function sendSlackMessage(news, url = process.env.SlackWebhookUrl) {  const body = JSON.stringify({    text: 'Following posts are trending on Hacker News:',    attachments: news.map(item => ({      'author_name': `${item.score} points by ${item.by}`,      title: item.title,      'title_link': item.url    }))  })
return rp.post(url, {    headers: {      'Content-Type': 'application/json'    },    body: body  })}
module.exports = sendSlackMessage

Now that the code is ready, let’s deploy the app and schedule messages.

现在代码已经准备好,让我们部署应用程序并安排消息。

部署,配置和测试应用 (Deploying, configuring, and testing the app)

We’ll use Claudia.js to deploy our function to AWS Lambda. Before we continue, make sure you follow this tutorial to install Claudia and configure AWS access credentials.

我们将使用Claudia.js将功能部署到AWS Lambda。 在继续之前,请确保您遵循本教程来安装Claudia并配置AWS访问凭证。

Also, you’d need to create the env.json file in your project folder, to define the Slack Webhook URL. This file should have similar content to the next code listing. Make sure you replace the generic URL with the one you received when you configured the Slack application.

另外,您需要在项目文件夹中创建env.json文件,以定义Slack Webhook URL。 该文件应具有与下一个代码清单相似的内容。 确保将通用URL替换为配置Slack应用程序时收到的URL。

{  "SlackWebhookUrl": "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"}

Now that everything is ready, run the following command in your terminal to deploy your app:

现在一切就绪,在终端中运行以下命令来部署您的应用程序:

claudia create --region eu-central-1 --handler index.handler --timeout 10 --set-env-from-json env.json

In this command, you do the following things:

在此命令中,您将执行以下操作:

  • Define the region where your Lambda function will be deployed. For the full list of supported regions, see the docs.

    定义将部署Lambda函数的区域 。 有关受支持区域的完整列表,请参阅docs

  • Define the handler file, which is a relative path to your entry point file, but with a .handler instead of .js extension.

    定义处理程序文件,该文件是您的入口点文件的相对路径,但具有.handler而不是.js扩展名。

  • Set the timeout, because default AWS Lambda is 3 seconds, but you need to do a few HTTP requests. To make it safe, increase the timeout to at least 10 seconds.

    设置timeout ,因为默认的AWS Lambda是3秒,但是您需要执行一些HTTP请求。 为了安全起见,请将超时时间增加到至少10秒。

  • Set the environment variables from the JSON file you prepared.

    从您准备的JSON文件中设置环境变量

After a few seconds, you’ll receive a JSON response like in the example below. You’ll also see claudia.json file in your project folder.

几秒钟后,您将收到一个JSON响应,如下例所示。 您还将在项目文件夹中看到claudia.json文件。

{  "lambda": {    "role": "scheduled-slack-messages-executor",    "name": "scheduled-slack-messages",    "region": "eu-central-1"  }}

This means that your AWS Lambda function is ready.

这意味着您的AWS Lambda函数已准备就绪。

The next step is to create a CloudWatch Event. Let’s say you want to receive a message every day at 10 AM CET, because your cron is running in the GMT time zone. Your cron command should look like this: cron(0 9 * * ? *).

下一步是创建CloudWatch Event。 假设您想每天CET AM 10收到一条消息,因为您的Cron正在GMT时区运行。 您的cron命令应如下所示: cron(0 9 * * ? *)

To setup an event every day at 10 AM, run the following command from your terminal:

要在每天的上午10点设置事件,请从终端运行以下命令:

aws events put-rule --name hackerNewsDigest --schedule-expression 'cron(0 9 * * ? *)'

This command will output the rule ARN, which you’ll need to save because you’ll need it in a second.

此命令将输出规则ARN,您将需要保存该规则,因为您在一秒钟之内将需要它。

Amazon Resource Names (ARNs) are unique identifiers of AWS resources. Read more about ARNs in the docs here.

亚马逊资源名称(ARN)是AWS资源的唯一标识符。 在此处阅读有关ARN的更多信息。

Now that your CloudWatch Event is ready, you need to permit it to trigger a Lambda function. To do so, run the following command from your terminal:

现在您的CloudWatch Event已准备就绪,您需要允许它触发Lambda函数。 为此,请从终端运行以下命令:

aws lambda add-permission \  --statement-id 'hackernews-scheduled-messages' \  --action 'lambda:InvokeFunction' \  --principal 'events.amazonaws.com' \  --source-arn ruleArn \  --function-name functionName \  --region region

In this command:

在此命令中:

  • ruleArn is the ARN of the CloudWatch Event rule you recieved after running the previous command.

    ruleArn是运行上一条命令后收到的CloudWatch Event规则的ARN。

  • functionName is the name of your function from your claudia.json file.

    functionNameclaudia.json文件中functionName的名称。

  • region is the region from your claudia.json file.

    region是您的claudia.json文件中的区域。

Your command will return a JSON response. Find the Resource in the response and copy the Lambda ARN. It should look like the following:

您的命令将返回JSON响应。 在响应中找到资源 ,然后复制Lambda ARN 。 它应如下所示:

  • arn:aws:lambda:eu-central-1:123456789012:function:scheduled-slack-messages

    arn:aws:lambda:eu-central-1:123456789012:function:scheduled-slack-messages

Finally, you’ll need to set the trigger by running the following command from your terminal:

最后,您需要通过从终端运行以下命令来设置触发器:

aws events put-targets --rule hackerNewsDigest --targets '[{ "Id": "1", "Arn": "your Lambda ARN" }]'

And that’s it, your scheduled Slack event is ready. Next day at 10 AM CET you should receive a message that looks like the following figure.

就是这样,您计划的Slack事件已准备就绪。 第二天,欧洲中部时间上午10点,您应该收到一条如下图所示的消息。

In case you can’t wait for 10 AM and you want to see the result earlier, run the claudia test-lambda command from your terminal. Make sure you navigate to your project folder first.

如果您不能等到上午10点,并且想早点看到结果,请从终端运行claudia test-lambda命令。 确保首先浏览到项目文件夹。

More similar articles are on their way. If you want to stay up-to-date with my new articles, or you have a topic you would love to read about, follow and contact me on twitter - twitter.com/slobodan_.

更多类似的文章正在酝酿中。 如果您想了解我的新文章,或者您想阅读一个主题, 请通过twitter-twitter.com/slobodan_与我联系。

As always, many thanks to my friend Aleksandar Simović for help and feeback on the article.

与往常一样,非常感谢我的朋友AleksandarSimović对本文的帮助和反馈。

All illustrations are created using SimpleDiagrams4 app.

所有插图都是使用SimpleDiagrams4应用程序创建的。

If you want to learn more about serverless apps in general, check out “Serverless Apps with Node and Claudia.js”, the book I wrote with Aleksandar Simovic for Manning Publications.

如果您想大致了解有关无服务器应用程序的更多信息,请查阅“我与Aleksandar Simovic为Manning Publications撰写的书“带有Node和Claudia.js的无服务器应用程序”。

Serverless Apps with Node and Claudia.jsFirst the buzzwords: Serverless computing. AWS Lambda. API Gateway. Node.js. Microservices. Cloud-hosted functions…www.manning.com

带有Node和Claudia.js的无服务器应用程序 首先流行的词:无服务器计算。 AWS Lambda。 API网关。 Node.js。 微服务。 云托管功能… www.manning.com

The book will teach you how to build and debug a real world serverless APIs (with DB, authentication and tests) using Node and Claudia.js. It also covers the migration of your existing app that is running on servers to a serverless app, how to build chatbots for Facebook Messenger and SMS (using Twilio), and Alexa skills.

这本书将教您如何使用Node和Claudia.js构建和调试真实的无服务器API(包括数据库,身份验证和测试)。 它还介绍了将服务器上运行的现有应用程序迁移到无服务器应用程序,如何为Facebook Messenger和SMS(使用Twilio)构建聊天机器人以及Alexa技能。

翻译自: https://www.freecodecamp.org/news/scheduling-slack-messages-using-aws-lambda-e56a8eb22818/

aws lambda使用

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值