【Azure 应用服务】本地创建Azure Function Kafka Trigger 函数和Kafka output的HTTP Trigger函数实验

简介: 【Azure 应用服务】本地创建Azure Function Kafka Trigger 函数和Kafka output的HTTP Trigger函数实验

问题描述

在上一篇博文(https://www.cnblogs.com/lulight/p/16525902.html)中,我们成功的以VM作为Kafka服务器运行,并且验证了从其他机器中远程访问。在本文中,将使用Visual Studio 2022创建Azure Function 作为生产者和消费者在本地进行验证

  • 生产者:使用HTTP Trigger函数,以 kafka output 作为输出
  • 消费者:使用Kafka Trigger函数

 

解题步骤

1:打开VS 2022,开始创建Azure Funciton工程

2:选择 Azure Function模板,并使用.NET 6.0作为运行时,然后选择 Kafka Trigger。其他值保持默认即可。保存。

3:   把BorkerList添加到本地配置文件中( local.settings.json ),然后修改正确的topic名称。因为Kafka服务器没有启用SSL和Password,所以这里 Protocol 和 AuthenticationMode 都需要修改为 NotSet。

local.setting.json 配置文件:

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "BrokerList": "xxx.xxx.xxx.xxx:9092",
    "KafkaPassword": "",
    "ConnectionString": ""
  }
}

 

KafkaTrigger Function代码:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Kafka;
using Microsoft.Extensions.Logging;
namespace FunctionApp2
{
    public class Function1
    {
        // KafkaTrigger sample 
        // Consume the message from "topic" on the LocalBroker.
        // Add `BrokerList` and `KafkaPassword` to the local.settings.json
        // For EventHubs
        // "BrokerList": "{EVENT_HUBS_NAMESPACE}.servicebus.windows.net:9093"
        // "KafkaPassword":"{EVENT_HUBS_CONNECTION_STRING}
        [FunctionName("Function1")]
        public void Run(
            [KafkaTrigger("BrokerList",
                          "test_topic",
                          Username = "$ConnectionString",
                          Password = "%KafkaPassword%",
                          Protocol = BrokerProtocol.NotSet,
                          AuthenticationMode = BrokerAuthenticationMode.NotSet,
                          ConsumerGroup = "$Default")] KafkaEventData<string>[] events,
            ILogger log)
        {
            foreach (KafkaEventData<string> eventData in events)
            {
                log.LogInformation($"C# Kafka trigger function processed a message: {eventData.Value}");
            }
        }
    }
}

4:同样,继续添加一个 Kafka output 的Function, (与第二步相同)。其他值保持默认即可。保存。

5:与第三步相同,修改正确的topic名称。因为Kafka服务器没有启用SSL和Password,所以这里 Protocol 和 AuthenticationMode 都需要修改为 NotSet。

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.Kafka;
using Microsoft.Extensions.Logging;
namespace FunctionApp2
{
    public class Function2
    {
        // KafkaOutputBinding sample
        // This KafkaOutput binding will create a my_topic "my_topic" on the LocalBroker if it doesn't exists.
        // Call this function then the KafkaTrigger will be trigged.
        [FunctionName("Function2")]
        public IActionResult Output(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            [Kafka("BrokerList",
                   "test_topic",
                   Username = "$ConnectionString",
                   Password = "%KafkaPassword%",
                   Protocol = BrokerProtocol.NotSet,
                   AuthenticationMode = BrokerAuthenticationMode.NotSet
            )] out string eventData,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string message = req.Query["message"];
            string responseMessage = string.IsNullOrEmpty(message)
                ? "This HTTP triggered function executed successfully. Pass a message in the query string"
                : $"Message {message} sent to the broker. This HTTP triggered function executed successfully.";
            eventData = $"Received message: {message}";
            return new OkObjectResult(responseMessage);
        }
    }
}

6:F5运行Function Project,使用HTTP Trigger的URL发送消息,然后用Kafka Trigger的函数接受消息。

整个步骤的示例动画:

 

参考文档

适用于 Azure Functions 的 Apache Kafka 绑定概述https://docs.azure.cn/zh-cn/azure-functions/functions-bindings-kafka?tabs=in-process%2Cportal&pivots=programming-language-csharp

 

【END】

相关文章
|
3月前
|
API C++
【Azure 环境】VS Code登录China Azure(Function)报错 An error occurred while signing in: invalid_request - AADSTS65002
An error occurred while signing in: invalid_request - AADSTS65002: Consent between first party application 'c27c220f-ce2f-4904-927d-333864217eeb' and first party resource '797f4846-ba00-4fd7-ba43-dac1f8f63013' must be configured via preauthorization - applications owned and operated by Microsoft mus
194 14
|
7月前
|
存储 安全 数据安全/隐私保护
【Azure Function App】在Function App中使用System Managed Identity访问Storage Account
本文介绍了如何在Azure Function中使用托管身份(Managed Identity)替代AzureWebJobsStorage连接函数应用到存储账户,以提高安全性并减少Access Key的使用。具体步骤包括:1) 启用系统分配的身份;2) 为函数应用授予存储访问权限,添加必要角色(如Storage Blob Data Contributor);3) 配置`AzureWebJobsStorage__blobServiceUri`参数指定Blob Service Uri。完成后删除旧配置,即可通过Managed Identity访问Storage Account。
226 19
|
2月前
|
数据安全/隐私保护
【Azure Function App】PowerShell Function 执行 Get-AzAccessToken 的返回值类型问题:System.String 与 System.Security.SecureString
将PowerShell Function部署到Azure Function App后,Get-AzAccessToken返回值类型在不同环境中有差异。正常为SecureString类型,但部分情况下为System.String类型,导致后续处理出错。解决方法是在profile.ps1中设置环境变量$env:AZUREPS_OUTPUT_PLAINTEXT_AZACCESSTOKEN=false,以禁用明文输出。
|
3月前
|
JSON 数据格式
【Azure 环境】当一个Azure Function资源创建很久了,是否可以获取到它的创建时间呢?
用户在尝试获取 Azure Function App 的创建时间时发现,资源 JSON 中缺少 `createdTime` 字段,仅能查看到 `lastModifiedTime`。同时,活动日志和 Azure Resource Graph 查询也未能提供创建时间信息。经解答,Azure 并未为所有资源类型记录创建时间,建议在部署时将创建时间作为标签记录。若创建时间在 90 天内,可通过部署日志间接获取。
154 7
|
4月前
|
网络协议 API 网络安全
【Azure Function App】发现部分请求Function App遇见 403.72 报错(请求Body>100KB)
在调用Azure Function的HTTP Trigger时,发送POST请求偶尔出现403错误,且响应为空、Header信息少。经排查发现,当请求Body大于100KB时会触发403.72错误,原因是启用了“Client Certificate mode”为“Optional Interactive User”。解决方法是将该模式设置为“Ignore”。由于TLS重新协商机制限制,大请求体无法正常处理,导致此问题。
152 1
|
6月前
|
安全 Linux 开发工具
【Azure Function】分享把Function App从.NET 6.0升级到.NET 8.0 Isolated的步骤
本文介绍了将Azure Function App从.NET 6.0升级到.NET 8.0 Isolated的步骤。.NET 6.0作为长期支持版本,生命周期至2024年11月结束。为确保持续支持,建议升级至更新版本。升级步骤包括安装.NET 8 SDK、更新Azure Functions Core Tools、修改项目文件目标框架为net8.0、更新兼容的NuGet包、本地测试以及重新发布到Azure。更多详细信息可参考官方文档。
283 10
|
10月前
|
C#
【Azure Function】Function App出现System.IO.FileNotFoundException异常
Exception while executing function: xxxxxxx,The type initializer for 'xxxxxx.Storage.Adls2.StoreDataLakeGen2Reading' threw an exception. Could not load file or assembly 'Microsoft.Extensions.Configuration, Version=9.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the
251 64
|
10月前
|
JSON C# 数据格式
【Azure Function】C#独立工作模式下参数类型 ServiceBusReceivedMessage 无法正常工作
Cannot convert input parameter 'message' to type 'Azure.Messaging.ServiceBus.ServiceBusReceivedMessage' from type 'System.String'.
205 73
|
9月前
|
JavaScript API
【Azure Function】Function App门户上的Test/Run返回错误:Failed to fetch
Running your function in portal requires the app to explicitly accept requests from https://portal.azure.cn. This is known as cross-origin resource sharing (CORS).Configure CORS to add https://portal.azure.cn to allowed origins.
227 7