You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Azure Function中为Service Bus Topic消息添加自定义属性

在Python Azure Function中为Service Bus Topic消息添加自定义属性

要让Python Azure Function发送的Service Bus Topic消息自动携带自定义属性,匹配SQL Filter投递到指定订阅,可通过Azure Service Bus SDK的Message对象的application_properties字段实现,具体操作如下:

1. 安装依赖包

确保Function项目中安装了Azure Service Bus SDK:

pip install azure-servicebus

2. 代码实现示例

以下是HTTP触发的Azure Function示例,演示发送带自定义属性的消息到Service Bus Topic:

import azure.functions as func
from azure.servicebus import ServiceBusClient, ServiceBusMessage
import os

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="send_topic_message")
def send_topic_message(req: func.HttpRequest) -> func.HttpResponse:
    # 从应用配置中读取Service Bus连接字符串和Topic名称
    CONNECTION_STR = os.environ.get("SERVICE_BUS_CONNECTION_STR")
    TOPIC_NAME = os.environ.get("SERVICE_BUS_TOPIC_NAME")

    try:
        # 创建Service Bus客户端和消息发送器
        servicebus_client = ServiceBusClient.from_connection_string(CONNECTION_STR)
        with servicebus_client:
            sender = servicebus_client.get_topic_sender(topic_name=TOPIC_NAME)
            with sender:
                # 构造消息并添加自定义属性
                message = ServiceBusMessage("订单创建通知")
                # 自定义属性需与Subscription的SQL Filter条件对应
                message.application_properties = {
                    "Department": "Sales",
                    "OrderType": "Online",
                    "Priority": 1
                }
                # 发送消息
                sender.send_messages(message)
        
        return func.HttpResponse("消息发送成功,已携带自定义属性", status_code=200)
    except Exception as e:
        return func.HttpResponse(f"发送失败: {str(e)}", status_code=500)

关键注意事项

  • application_properties是ServiceBusMessage的字典属性,用于存储自定义键值对,这些属性会被Service Bus Topic的SQL Filter识别。
  • 自定义属性的类型需与Subscription中SQL Filter的条件匹配:例如Filter设置为Department = 'Sales',属性值需为字符串;若Filter是Priority > 0,属性值需为数值类型。
  • 不要硬编码连接字符串,建议通过Azure Function的应用配置(Configuration)添加环境变量,再通过os.environ.get读取,保障安全性。

内容的提问来源于stack exchange,提问作者Syamala Kumar Rama Koti Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:50:30