Share via


將訊息傳送至 Pub/Sub 主題

適用於:開發人員 |進階版

publish-to-dapr 原則會指示 APIM 閘道,將訊息傳送至 Dapr 發佈/訂閱的主題。 此原則會藉由發出 HTTP POST 要求到 http://localhost:3500/v1.0/publish/{{pubsub-name}}/{{topic}},同時取代範本參數及新增原則陳述式中所指定的內容,而完成作業。

該原則假設 Dapr 會在與閘道相同的 Pod 中的 Sidecar 容器內執行。 Dapr 執行階段會實作 Pub/Sub 的語意。 深入了解 Dapr 與 APIM 整合

注意

請依照原則陳述式中提供的順序,來設定原則的元素和子元素。 深入了解如何設定或編輯 APIM 原則

原則陳述式

<publish-to-dapr pubsub-name="pubsub-name" topic="topic-name" ignore-error="false|true" response-variable-name="resp-var-name" timeout="in seconds" template="Liquid" content-type="application/json">
    <!-- message content -->
</publish-to-dapr>

屬性

屬性 描述 是必要欄位 預設
pubsub-name PubSub 目標元件的名稱。 在 Dapr 中對應至 pubsubname 的參數。 如果不存在,topic 屬性值必須為 pubsub-name/topic-name 的格式。 允許使用原則運算式。 No
主題 主題的名稱。 在 Dapr 中對應至 topic 參數。 允許使用原則運算式。 Yes N/A
ignore-error 如果設定為 true,則指示該原則不要在從 Dapr 執行階段收到錯誤時觸發 on-error 區段。 不允許使用原則運算式。 No false
response-variable-name 要用於儲存 Dapr 執行階段回應的變數集合項目名稱。 不允許使用原則運算式。 No
timeout 等候 Dapr 執行階段回應的時間 (以秒計)。 其範圍可從 1 至 240 秒 允許使用原則運算式。 No 5
template 用來轉換訊息內容的範本化引擎。 「Liquid」是唯一支援的值。 No
Content-Type 訊息內容的類型。 「application/json」是唯一支援的值。 No

使用方式

使用注意事項

必須在自我裝載閘道中啟用 Dapr 支援。

範例

下列範例,會示範如何將目前要求的本文傳送至「orders」Pub/Sub元件的「new」主題。 從 Dapr 執行階段收到的回應會儲存在內容物件中變數集合的「dapr-response」專案內。

例如,如果 Dapr 執行時間找不到目標主題,並回應錯誤,則會觸發「on-error」區段。 從 Dapr 執行階段所收到的回應,將逐字傳回至呼叫端。 否則,會傳回預設200 OK回應。

「後端」區段是空的,而且該要求不會轉送至後端。

<policies>
     <inbound>
        <base />
        <publish-to-dapr
           pubsub-name="orders"
               topic="new"
               response-variable-name="dapr-response">
            @(context.Request.Body.As<string>())
        </publish-to-dapr>
    </inbound>
    <backend>
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
        <return-response response-variable-name="pubsub-response" />
    </on-error>
</policies>

如需使用原則的詳細資訊,請參閱: