桌面应用程序 azure_如何开始使用Microsoft Azure-功能应用程序,HTTP触发器和事件队列...

桌面应用程序 azure

"Serverless" architecture is all the rage in tech land at the moment, including heavy usage at my new workplace.

“无服务器”架构目前在科技界风靡一时,包括在我的新工作场所中大量使用。

Microsoft jumped into this space with Azure a while back. Their portal, where all the services are grouped and "organized", offers so many services it feels nearly impossible to be an expert.

微软不久前就通过Azure进入了这个领域。 他们的门户网站将所有服务分组和“组织”在一起,提供了如此多的服务,成为专家几乎感觉不到。

I'll cover function apps, triggers, bindings, and event queues, enough to get a web developer started on something great in the cloud.

我将介绍功能应用程序,触发器,绑定和事件队列 ,足以使Web开发人员着手开发云中的出色功能。

Tulip fields near Amsterdam

Two months ago I had never worked with any of these technologies, but I am loving how clean, clearly separated, and async these tools can be. Azure services have some flaws (portal speed, UI problems, and as you scale, difficulty in understanding what is dragging down the system) but on the whole the technology is easy to use and very powerful.

两个月前,我从未使用过任何这些技术,但是我喜欢这些工具可以做到多么干净,清晰地分离和异步。 Azure服务存在一些缺陷(门户速度,UI问题,以及随着扩展而导致的问题,难以理解导致系统崩溃的原因),但总体而言,该技术易于使用且非常强大。

功能应用 (Function Apps)

The first thing you'll do to get started is create a Function App. In Azure's world, this is a grouping of related functionality. You will create discrete functions inside the Function App. Each Function App has access to a storage container.

首先,您要做的是创建一个功能应用程序。 在Azure的世界中,这是一组相关功能。 您将在Function App中创建离散函数 。 每个功能应用程序都可以访问存储容器。

Creating a function app in Azure's web portal

Function app settings

From the portal (after account setup and payment), you'll click "Create a Resource" at the very top, and select Function App. Give your app a name, choose a language to write your code in (I chose Node for Javascript), and keep the rest of the settings as they are.

从门户网站(设置和付款帐户后),您将单击最顶部的“创建资源”,然后选择Function App。 为您的应用命名,选择一种语言来编写代码(我为Java选择了Node),其余设置保持原样。

It takes a minute to deploy a new Function App - you can click on the notification in the upper right to watch progress and get an easy link when it's ready.

部署新的Function App需要一分钟-您可以单击右上角的通知以查看进度,并在准备就绪时获得简单链接。

增加功能 (Adding functionality)

Once the Function App is ready, click the plus next to Functions. Select "In Portal editor" and "Webhook / API". We'll be doing the most basic setup possible. CI/CD deployments and such are outside the scope of this tutorial, but of course you can version control your work using git tools and deploy through a pipeline.

准备好功能应用程序后,单击“功能”旁边的加号。 选择“在门户网站编辑器中”和“ Webhook / API”。 我们将进行最基本的设置。 CI / CD部署等不在本教程的讨论范围之内,但是您当然可以使用git工具进行版本控制并通过管道进行部署。

editing-azure-function-in-portal

Azure function app logs after http trigger

绑定 (Bindings)

After you create your function, you'll get an index.js and a function.json. You can access these to the right of your in-portal editor under "View Files".

创建函数后,您将获得一个index.js和一个function.json 。 您可以在“查看文件”下的门户编辑器右侧访问这些文件。

Let's look at function.json first - it's the configuration file for your function. Here's the file as the portal will spit it out:

首先让我们看一下function.json -这是您的函数的配置文件。 这是门户网站将吐出的文件:

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ],
  "disabled": false
}

Bindings are Azure's handy way to connect to various services and resources without needing to do a lot of setup.

绑定是Azure连接到各种服务和资源的便捷方法,无需进行大量设置。

httpTrigger (httpTrigger)

  • Change authLevel to "anonymous" and we won't need a key to call our function.

    authLevel更改为"anonymous" ,我们将不需要键来调用我们的函数。

  • The type is httpTrigger - that means we're going to generate

    typehttpTrigger这意味着我们将生成

    an endpoint we can use to call this function (more below).

    我们可以用来调用此功能的端点(更多信息请参见下文)。

  • The direction can be either in or out - indicating input or output to/from our function.

    direction可以是inout -指示从我们的函数输入或输出到/。

  • The trigger will call the function with parameters supplied. We can call the binding whatever we want, but convention says we name the input req for request and the output res for response.

    触发器将使用提供的参数来调用该函数。 我们可以随意调用绑定,但是习惯上说我们将输入req命名为请求,将输出res命名为响应。

  • Methods are how we can call this function. I'll delete post, as we won't need it.

    Methods是我们如何调用此函数的方法。 我将删除post ,因为我们不需要它。

The next binding is also type http, direction out, because this is how we'll send a response. If you want to disable the function, you can do it here in the function.json or in the UI of the portal.

下一个绑定也是type http ,direction out ,因为这是我们发送响应的方式。 如果要禁用该功能,可以在此处在function.json或门户的UI中进行。

在功能代码中使用绑定 (Using bindings in the function code)

We can use the example code provided by Azure to show how bindings work. I've simplified Azure's code but you should have something very similar in your index.js if you're following along:

我们可以使用Azure提供的示例代码来显示绑定的工作方式。 我简化了Azure的代码,但是如果您遵循以下步骤,则应该在index.js有一些非常相似的内容:

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    if (req.query.name) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + req.query.name
        };
    }
    else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
};

Sending a request through Postman to our Azure function app

Here you can see we have a simple web hook. We can watch it work quickly by clicking on "Get function URL" and sending a request with cURL or Postman. So what's going on?

在这里您可以看到我们有一个简单的Web挂钩。 我们可以通过单击“获取功能URL”并使用cURL或Postman发送请求来快速查看其工作情况。 发生什么了?

Azure function app logs receiving an http trigger

Through Azure magic, our function has been called with context and the req that we sent. The context allows us access to the bindings we saw in function.json and the req becomes input for our function.

通过Azure魔术,已经使用context和发送的req调用了我们的函数。 context允许我们访问在function.json看到的绑定,并且req成为函数的输入。

More Azure magic handles the response. We simply set the status to our requirements, and the body appropriately. Azure handles the rest. (Note that if you are sending JSON or other non-string response objects, you'll have to set the headers.)

更多Azure魔术可以处理响应。 我们只需根据自己的要求设置status ,并适当地设置body 。 Azure负责其余的工作。 (请注意,如果要发送JSON或其他非字符串响应对象,则必须设置标头。)

We can see all this working in the logs. You'll find them at the very bottom of the page under the index.js code. Note that console.log won't help you here - you'll need to use context.log.

我们可以在日志中看到所有这些工作。 您可以在页面底部index.js代码下找到它们。 请注意, console.log在这里无济于事-您需要使用context.log

And that's it! We have a web hook running in the "cloud".

就是这样! 我们有一个在“云”中运行的网络挂钩。

环境变量 (Env variables)

We probably won't get far without having some secrets we use to connect to databases, external APIs, and other services. You can keep those variables under "Configuration" when you click the name of your Function App (as opposed to Functions). Azure will automatically put a bunch in there to deal with your Function App storage and Application Insights (monitoring).

如果没有用于连接数据库,外部API和其他服务的一些秘密,我们可能不会走得太远。 当您单击Function App的名称(与Function相对)时,可以将这些变量保留在“配置”下。 Azure将自动在其中放置一些功能来处理您的Function App存储和Application Insights(监视)。

其他绑定 (Other bindings)

There are dozens of bindings that can be used. Azure can connect to several different types of databases, and you can create a trigger for a new document being created. Likewise, this method could receive a payload that would create a record with an out binding.

可以使用数十种绑定。 Azure可以连接到几种不同类型的数据库,并且可以为要创建的新文档创建触发器。 同样,此方法可以接收将创建带有out绑定的记录的有效负载。

Another interesting binding is an event, which I'll cover next.

另一个有趣的绑定是一个event ,我将在下面讨论。

事件队列 (Event queues)

A request and response is great, but what if we want to create an asynchronous event from an HTTP binding?

请求和响应很棒,但是如果我们想通过HTTP绑定创建异步事件怎么办?

Say we are creating a user. After that user is created, we want to send an email to welcome them to our service.

假设我们正在创建一个用户。 创建该用户之后,我们希望发送电子邮件以欢迎他们使用我们的服务。

But if something is wrong with our send-email code, we would never want that to get in the way of creating a user or responding to the customer. We can create async messaging through an event queue.

但是,如果我们的发送电子邮件代码出了点问题,我们绝不会希望这种方式妨碍创建用户或响应客户。 我们可以通过事件队列创建异步消息传递。

I won't get too deep into how queues work, but the idea is quite simple: one method puts messages into a line, and another peels them off and does something with them (last in, first out). When the queue is empty, anything that listens to it is quiet.

我不会对队列的工作原理有很深的了解,但是这个想法很简单:一种方法将消息放入一行,另一种将消息剥离并对其进行处理(后进先出)。 当队列为空时,任何可以监听的内容都是安静的。

Azure has functionality for different types of queues, including the more complex Service Bus.

Azure具有适用于不同类型队列的功能,包括更复杂的服务总线。

创建队列 (Creating the queue)

The first thing we'll do is create a queue that our functions can push and read from. If you click "Home" in the breadcrumbs, you should see your Function App name in recent resources.

我们要做的第一件事是创建一个队列,我们​​的函数可以推送和读取该队列。 如果单击面包屑中的“主页”,则应该在最近的资源中看到您的Function App名称。

The link here is actually to the "Resource group" - a collection of all the items you created with the Function App. Click in, then select your storage (it looks like a database table).

此处的链接实际上是“资源组”的链接-您使用Function App创建的所有项目的集合。 单击,然后选择您的存储(它看起来像数据库表)。

Now find the Queues tab, click "+Queue", then create a queue for your function app. Note that you can have as many queues as you like. You can also create items in your queue manually for testing your functions independently.

现在,找到“队列”选项卡,单击“ +队列”,然后为您的函数应用创建队列。 请注意,您可以根据需要拥有任意数量的队列。 您还可以手动在队列中创建项目以独立测试功能。

Azure function app resource group

队列绑定 (Queue bindings)

Add a new function (click the + icon) and select "Azure Queue Storage trigger". This will prompt you to install an Event Hub extension, then give your function a name - you can ignore the other settings for now. Here's the function.json code for our new bindings:

添加一个新功能(单击+图标),然后选择“ Azure Queue Storage触发器”。 这将提示您安装Event Hub扩展,然后为您的函数命名-您现在可以忽略其他设置。 这是我们新绑定的function.json代码:

{
  "bindings": [
    {
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "js-queue-items",
      "connection": "AzureWebJobsStorage"
    }
  ],
  "disabled": false
}

We'll use the storage we created for this function app to keep a queue of events. The index.js takes in the item from the queue and executes with it. We don't need to do much with our function, so we can just keep the demo code from Azure:

我们将使用为此功能应用程序创建的存储来保留事件队列。 index.js从队列中取出项目并执行。 我们不需要对我们的功能做太多事情,因此我们可以保留Azure的演示代码:

module.exports = async function (context, myQueueItem) {
    context.log('JavaScript queue trigger function processed work item', myQueueItem);
};

Azure function app logs after queue trigger

将项目添加到队列 (Adding an item to the queue)

Your queue trigger function is running, but it won't do anything until we add an item to our queue. We can do this by adjusting our first function to put an item in the queue when the web hook is called.

您的队列触发功能正在运行,但是在我们向队列添加项目之前它不会做任何事情。 为此,我们可以通过调整第一个函数来在调用Web挂钩时将项目放入队列中来实现。

{ bindings: [...],
    {
      "name": "myQueueItem",
      "type": "queue",
      "direction": "out",
      "queueName": "js-queue-items",
      "connection": "AzureWebJobsStorage"
    }
}

Now we can update our code to add an item to the queue:

现在,我们可以更新代码以将项目添加到队列中:

[...]
    if (req.query.name) {
        context.bindings.myQueueItem = {
            name: req.query.name,
            ts: new Date()
        }
[...]

If you open your functions in separate windows, you can watch the whole thing happen in the logs for each function. Send your request, watch it be consuming in the http trigger, then the queue trigger will pick up the message placed by the first function. Cool, right?

如果在单独的窗口中打开函数,则可以在每个函数的日志中看到整个过程。 发送您的请求,查看它是否在http触发器中消耗,然后队列触发器将提取第一个函数放置的消息。 酷吧?

This is some powerful stuff for creating asynchronous jobs in a way that prevents your functions from taking each other out. In a "monolith" model, if one function misbehaves, it can prevent others from executing. In this model, if there is something wrong with the queue trigger, it won't prevent the server from responding appropriately. Naturally, this adds a layer of complexity and consideration that doesn't exist in a monolith - there are always trade-offs.

这是一些强大的功能,可用于创建异步作业,从而防止您的函数相互淘汰。 在“整体”模型中,如果一个函数行为不当,则可能阻止其他函数执行。 在此模型中,如果队列触发器出现问题,则不会阻止服务器适当地响应。 自然,这增加了整体中不存在的复杂性和考虑层-总是存在权衡取舍。

But if we go back to our theoretical use-case where we are creating a new user with an http trigger, image having 10 queues to do various things. Our http trigger might create a document in the database and return success in the request.

但是,如果我们回到理论上的用例,即用http触发器创建一个新用户,则该图像具有10个队列来执行各种操作。 我们的http触发器可能会在数据库中创建一个文档,并在请求中返回成功。

The same job might add to a queue about sending an email, triggering a coupon SMS to send in an hour, putting a Slack message to a marketing team, or any of a million other things that might need to happen when a new user is created. If any one of them fails (Slack is down?), the others go on happily on their way.

相同的工作可能会增加有关发送电子邮件,触发优惠券SMS在一小时内发送,向市场营销团队发送Slack消息或创建新用户时可能需要发生的其他百万种事情中的队列。 。 如果其中任何一个发生故障(Slack掉线了吗?),其他两个就继续快乐地前进。

This article has only brushed the surface of what's available. I'm looking forward to exploring more of what Azure can do. Let me know if you have some tips for what to build next!

本文仅介绍了可用的内容。 我期待探索更多Azure可以做什么。 如果您有一些下一步的建议,请告诉我!

You can read more of my articles on my blog at wilkie.tech.

您可以在wilkie.tech的博客上阅读更多我的文章。

翻译自: https://www.freecodecamp.org/news/getting-started-with-microsoft-azure/

桌面应用程序 azure

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值