Azure Functions における Azure Service Bus のバインドAzure Service Bus bindings for Azure Functions
この記事では、Azure Functions で Azure Service Bus のバインドを連携する方法について説明します。This article explains how to work with Azure Service Bus bindings in Azure Functions. Azure Functions は、Service Bus のキューおよびトピックのトリガーおよび出力バインドをサポートしています。Azure Functions supports trigger and output bindings for Service Bus queues and topics.
これは、Azure Functions の開発者向けリファレンス情報です。This is reference information for Azure Functions developers. Azure Functions を初めて使用する場合は、先に次のリソースを参照してください。If you're new to Azure Functions, start with the following resources:
- 最初の関数を作成する: C#、JavaScript、Java、PythonCreate your first function: C#, JavaScript, Java, or Python.
- Azure Functions 開発者向けリファレンスAzure Functions developer reference.
- 言語固有のリファレンス: C#、C# script、F#、Java、JavaScript、PythonLanguage-specific reference: C#, C# script, F#, Java, JavaScript, or Python.
- Azure Functions でのトリガーとバインドの概念Azure Functions triggers and bindings concepts.
- Azure Functions をローカルでコーディングしてテストするCode and test Azure Functions locally.
パッケージ - Functions 1.xPackages - Functions 1.x
Service Bus のバインドは Microsoft.Azure.WebJobs.ServiceBus NuGet パッケージ、バージョン 2.x で提供されます。The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.ServiceBus NuGet package, version 2.x.
次の表に、各開発環境でこのバインディングのサポートを追加する方法を示します。The following table tells how to add support for this binding in each development environment.
開発環境Development environment | サポートを追加するバージョン:To add support in Functions 1.xFunctions 1.x |
---|---|
ローカル開発 - C# クラス ライブラリLocal development - C# class library | パッケージをインストールするInstall the package |
ローカル開発で - C# スクリプト、JavaScript、F#Local development - C# script, JavaScript, F# | 自動Automatic |
Portal 開発Portal development | 自動Automatic |
パッケージ - Functions 2.xPackages - Functions 2.x
Service Bus のバインドは Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet パッケージ、バージョン 3.x で提供されます。The Service Bus bindings are provided in the Microsoft.Azure.WebJobs.Extensions.ServiceBus NuGet package, version 3.x. パッケージのソース コードは、azure-functions-servicebus-extension GitHub リポジトリにあります。Source code for the package is in the azure-functions-servicebus-extension GitHub repository.
注意
バージョン 2.x では、ServiceBusTrigger
インスタンスで構成されたトピックまたはサブスクリプションが作成されることはありません。Version 2.x does not create the topic or subscription configured in the ServiceBusTrigger
instance. バージョン 2.x は、Microsoft.Azure.ServiceBus に基づいており、キューの管理を処理することはありません。Version 2.x is based on Microsoft.Azure.ServiceBus and does not handle queue management.
次の表に、各開発環境でこのバインディングのサポートを追加する方法を示します。The following table tells how to add support for this binding in each development environment.
開発環境Development environment | サポートを追加するバージョン:To add support in Functions 2.xFunctions 2.x |
---|---|
ローカル開発 - C# クラス ライブラリLocal development - C# class library | パッケージをインストールするInstall the package |
ローカル開発で - C# スクリプト、JavaScript、F#、Java、PythonLocal development - C# script, JavaScript, F#, Java and Python | 拡張機能を登録するRegister the extension |
Portal 開発Portal development | 出力バインドの追加時にインストールするInstall when adding output binding |
関数アプリ プロジェクトを再発行せずにポータルで既存のバインディング拡張機能を更新する方法については、拡張機能の更新に関するページを参照してください。To learn how to update existing binding extensions in the portal without having to republish your function app project, see Update your extensions.
トリガーTrigger
Service Bus トリガーを使用して、Service Bus キューまたはトピックからのメッセージに応答します。Use the Service Bus trigger to respond to messages from a Service Bus queue or topic.
トリガー - 例Trigger - example
言語固有の例をご覧ください。See the language-specific example:
トリガー - C# の例Trigger - C# example
次の例は、メッセージ メタデータを読み取り、Service Bus キュー メッセージをログに記録する C# 関数を示しています。The following example shows a C# function that reads message metadata and logs a Service Bus queue message:
[FunctionName("ServiceBusQueueTriggerCSharp")]
public static void Run(
[ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")]
string myQueueItem,
Int32 deliveryCount,
DateTime enqueuedTimeUtc,
string messageId,
ILogger log)
{
log.LogInformation($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
log.LogInformation($"DeliveryCount={deliveryCount}");
log.LogInformation($"MessageId={messageId}");
}
トリガー - C# スクリプトの例Trigger - C# script example
次の例は、function.json ファイルの Service Bus トリガー バインドと、そのバインドが使用される C# スクリプト関数を示しています。The following example shows a Service Bus trigger binding in a function.json file and a C# script function that uses the binding. この機能はメッセージ メタデータを読み取り、Service Bus のキュー メッセージをログに記録します。The function reads message metadata and logs a Service Bus queue message.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"name": "myQueueItem",
"type": "serviceBusTrigger",
"direction": "in"
}
],
"disabled": false
}
C# スクリプト コードを次に示します。Here's the C# script code:
using System;
public static void Run(string myQueueItem,
Int32 deliveryCount,
DateTime enqueuedTimeUtc,
string messageId,
TraceWriter log)
{
log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");
log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
log.Info($"DeliveryCount={deliveryCount}");
log.Info($"MessageId={messageId}");
}
トリガー - F# の例Trigger - F# example
次の例は、function.json ファイルの Service Bus トリガー バインドと、そのバインドが使用される F# 関数を示しています。The following example shows a Service Bus trigger binding in a function.json file and an F# function that uses the binding. この関数は、Service Bus キュー メッセージを記録します。The function logs a Service Bus queue message.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"name": "myQueueItem",
"type": "serviceBusTrigger",
"direction": "in"
}
],
"disabled": false
}
F# スクリプト コードを次に示します。Here's the F# script code:
let Run(myQueueItem: string, log: ILogger) =
log.LogInformation(sprintf "F# ServiceBus queue trigger function processed message: %s" myQueueItem)
トリガー - Java の例Trigger - Java example
次の Java 関数は、Java 関数ランタイム ライブラリからの @ServiceBusQueueTrigger
注釈を使用して、Service Bus キュー トリガーの構成について記述します。The following Java function uses the @ServiceBusQueueTrigger
annotation from the Java functions runtime library to describe the configuration for a Service Bus queue trigger. この関数は、キューにあるメッセージを取得し、ログに追加します。The function grabs the message placed on the queue and adds it to the logs.
@FunctionName("sbprocessor")
public void serviceBusProcess(
@ServiceBusQueueTrigger(name = "msg",
queueName = "myqueuename",
connection = "myconnvarname") String message,
final ExecutionContext context
) {
context.getLogger().info(message);
}
Service Bus トピックにメッセージが追加されたときに、Java 関数もトリガーできます。Java functions can also be triggered when a message is added to a Service Bus topic. 次の例では、トリガー構成を記述する @ServiceBusTopicTrigger
注釈を使用します。The following example uses the @ServiceBusTopicTrigger
annotation to describe the trigger configuration.
@FunctionName("sbtopicprocessor")
public void run(
@ServiceBusTopicTrigger(
name = "message",
topicName = "mytopicname",
subscriptionName = "mysubscription",
connection = "ServiceBusConnection"
) String message,
final ExecutionContext context
) {
context.getLogger().info(message);
}
トリガー - JavaScript の例Trigger - JavaScript example
次の例は、function.json ファイルの Service Bus トリガー バインドと、そのバインドが使用される JavaScript 関数を示しています。The following example shows a Service Bus trigger binding in a function.json file and a JavaScript function that uses the binding. この機能はメッセージ メタデータを読み取り、Service Bus のキュー メッセージをログに記録します。The function reads message metadata and logs a Service Bus queue message.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"name": "myQueueItem",
"type": "serviceBusTrigger",
"direction": "in"
}
],
"disabled": false
}
JavaScript スクリプト コードを次に示します。Here's the JavaScript script code:
module.exports = function(context, myQueueItem) {
context.log('Node.js ServiceBus queue trigger function processed message', myQueueItem);
context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
context.log('DeliveryCount =', context.bindingData.deliveryCount);
context.log('MessageId =', context.bindingData.messageId);
context.done();
};
トリガー - Python の例Trigger - Python example
次の例では、トリガーを使用して ServiceBus キュー メッセージを読み取る方法を示します。The following example demonstrates how to read a ServiceBus queue message via a trigger.
ServiceBus のバインディングは function.json で定義され、そこで type は serviceBusTrigger
に設定されます。A ServiceBus binding is defined in function.json where type is set to serviceBusTrigger
.
{
"scriptFile": "__init__.py",
"bindings": [
{
"name": "msg",
"type": "serviceBusTrigger",
"direction": "in",
"queueName": "inputqueue",
"connection": "AzureServiceBusConnectionString"
}
]
}
_init_.py のコードによってパラメーターが func.ServiceBusMessage
として宣言され、関数でキュー メッセージを読み取ることができるようになります。The code in _init_.py declares a parameter as func.ServiceBusMessage
which allows you to read the queue message in your function.
import azure.functions as func
import logging
import json
def main(msg: func.ServiceBusMessage):
logging.info('Python ServiceBus queue trigger processed message.')
result = json.dumps({
'message_id': msg.message_id,
'body': msg.get_body().decode('utf-8'),
'content_type': msg.content_type,
'expiration_time': msg.expiration_time,
'label': msg.label,
'partition_key': msg.partition_key,
'reply_to': msg.reply_to,
'reply_to_session_id': msg.reply_to_session_id,
'scheduled_enqueue_time': msg.scheduled_enqueue_time,
'session_id': msg.session_id,
'time_to_live': msg.time_to_live,
'to': msg.to,
'user_properties': msg.user_properties,
})
logging.info(result)
トリガー - 属性Trigger - attributes
C# クラス ライブラリでは、以下の属性を使用して Service Bus トリガーを構成します。In C# class libraries, use the following attributes to configure a Service Bus trigger:
ServiceBusTriggerAttributeServiceBusTriggerAttribute
属性のコンストラクターは、キューの名前、またはトピックとサブスクリプションを受け取ります。The attribute's constructor takes the name of the queue or the topic and subscription. Azure Functions バージョン 1.x では、接続のアクセス権を指定することもできます。In Azure Functions version 1.x, you can also specify the connection's access rights. アクセス権を指定しない場合、既定値は
Manage
になります。If you don't specify access rights, the default isManage
. 詳細については、「トリガー - 構成」セクションをご覧ください。For more information, see the Trigger - configuration section.文字列パラメーターで使用される属性を示す例は次のとおりです。Here's an example that shows the attribute used with a string parameter:
[FunctionName("ServiceBusQueueTriggerCSharp")] public static void Run( [ServiceBusTrigger("myqueue")] string myQueueItem, ILogger log) { ... }
次の例で示すように、
Connection
プロパティを設定して、使用する Service Bus アカウントを指定できます。You can set theConnection
property to specify the Service Bus account to use, as shown in the following example:[FunctionName("ServiceBusQueueTriggerCSharp")] public static void Run( [ServiceBusTrigger("myqueue", Connection = "ServiceBusConnection")] string myQueueItem, ILogger log) { ... }
完全な例については、「トリガー - C# の例」を参照してください。For a complete example, see Trigger - C# example.
ServiceBusAccountAttributeServiceBusAccountAttribute
使用する Service Bus アカウントを指定する別の方法を示します。Provides another way to specify the Service Bus account to use. コンストラクターは、Service Bus 接続文字列を含むアプリ設定の名前を受け取ります。The constructor takes the name of an app setting that contains a Service Bus connection string. 属性は、パラメーター、メソッド、またはクラス レベルで適用できます。The attribute can be applied at the parameter, method, or class level. 次の例では、クラス レベルとメソッド レベルを示します。The following example shows class level and method level:
[ServiceBusAccount("ClassLevelServiceBusAppSetting")] public static class AzureFunctions { [ServiceBusAccount("MethodLevelServiceBusAppSetting")] [FunctionName("ServiceBusQueueTriggerCSharp")] public static void Run( [ServiceBusTrigger("myqueue", AccessRights.Manage)] string myQueueItem, ILogger log) { ... }
使用する Service Bus アカウントは、次の順序で決定されます。The Service Bus account to use is determined in the following order:
ServiceBusTrigger
属性のConnection
プロパティ。TheServiceBusTrigger
attribute'sConnection
property.ServiceBusTrigger
属性と同じパラメーターに適用されたServiceBusAccount
属性。TheServiceBusAccount
attribute applied to the same parameter as theServiceBusTrigger
attribute.- 関数に適用される
ServiceBusAccount
属性。TheServiceBusAccount
attribute applied to the function. - クラスに適用される
ServiceBusAccount
属性。TheServiceBusAccount
attribute applied to the class. - "AzureWebJobsServiceBus" アプリの設定。The "AzureWebJobsServiceBus" app setting.
トリガー - 構成Trigger - configuration
次の表は、function.json ファイルと ServiceBusTrigger
属性で設定したバインド構成のプロパティを説明しています。The following table explains the binding configuration properties that you set in the function.json file and the ServiceBusTrigger
attribute.
function.json のプロパティfunction.json property | 属性のプロパティAttribute property | 説明Description |
---|---|---|
typetype | 該当なしn/a | "serviceBusTrigger" に設定する必要があります。Must be set to "serviceBusTrigger". このプロパティは、Azure Portal でトリガーを作成するときに自動で設定されます。This property is set automatically when you create the trigger in the Azure portal. |
directiondirection | 該当なしn/a | "in" に設定する必要があります。Must be set to "in". このプロパティは、Azure Portal でトリガーを作成するときに自動で設定されます。This property is set automatically when you create the trigger in the Azure portal. |
namename | 該当なしn/a | 関数コード内のキューまたはトピック メッセージを表す変数の名前。The name of the variable that represents the queue or topic message in function code. "$return" に設定して、関数の戻り値を参照します。Set to "$return" to reference the function return value. |
queueNamequeueName | QueueNameQueueName | 監視するキューの名前。Name of the queue to monitor. トピックではなくキューを監視する場合にのみ設定します。Set only if monitoring a queue, not for a topic. |
topicNametopicName | TopicNameTopicName | 監視するトピックの名前。Name of the topic to monitor. キューではなくトピックを監視する場合にのみ設定します。Set only if monitoring a topic, not for a queue. |
subscriptionNamesubscriptionName | SubscriptionNameSubscriptionName | 監視するサブスクリプションの名前。Name of the subscription to monitor. キューではなくトピックを監視する場合にのみ設定します。Set only if monitoring a topic, not for a queue. |
connectionconnection | ConnectionConnection | このバインドに使用する Service Bus 接続文字列を含むアプリ設定の名前です。The name of an app setting that contains the Service Bus connection string to use for this binding. アプリ設定の名前が "AzureWebJobs" で始まる場合は、名前の残りの部分のみを指定できます。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name. たとえば、connection を "MyServiceBus" に設定した場合、Functions ランタイムは "AzureWebJobsMyServiceBus" という名前のアプリ設定を探します。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." connection を空のままにした場合、Functions ランタイムは、アプリ設定内の "AzureWebJobsServiceBus" という名前の既定の Service Bus 接続文字列を使用します。If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".接続文字列は、管理資格情報の取得に関する記事の手順に従って取得します。To obtain a connection string, follow the steps shown at Get the management credentials. 接続文字列は、特定のキューまたはトピックに限らず、Service Bus 名前空間のものである必要があります。The connection string must be for a Service Bus namespace, not limited to a specific queue or topic. |
accessRightsaccessRights | Access (アクセス)Access | 接続文字列のアクセス権。Access rights for the connection string. 使用できる値は manage と listen です。Available values are manage and listen . 既定値は manage で、connection が管理アクセス許可を持つことを示します。The default is manage , which indicates that the connection has the Manage permission. 管理アクセス許可を持たない接続文字列を使用する場合は、accessRights を "listen" に設定します。If you use a connection string that does not have the Manage permission, set accessRights to "listen". 設定しないと、Functions ランタイムが管理権限を必要とする操作の試行に失敗する可能性があります。Otherwise, the Functions runtime might fail trying to do operations that require manage rights. 最新バージョンの Storage SDK が管理の操作をサポートしていないため、Azure Functions バージョン 2.x ではこのプロパティを利用できません。In Azure Functions version 2.x, this property is not available because the latest version of the Storage SDK doesn't support manage operations. |
ローカルで開発している場合、アプリ設定は local.settings.json ファイルに保存されます。When you're developing locally, app settings go into the local.settings.json file.
トリガー - 使用方法Trigger - usage
C# と C# スクリプトでは、キューまたはトピック メッセージに次のパラメーター型を使用できます。In C# and C# script, you can use the following parameter types for the queue or topic message:
string
- メッセージがテキストである場合。string
- If the message is text.byte[]
- バイナリ データの場合に便利です。byte[]
- Useful for binary data.- カスタム型 - メッセージに JSON が含まれている場合、Azure Functions は JSON データの逆シリアル化を試みます。A custom type - If the message contains JSON, Azure Functions tries to deserialize the JSON data.
BrokeredMessage
- BrokeredMessage.GetBody<T>() メソッドで逆シリアル化されたメッセージを返します。BrokeredMessage
- Gives you the deserialized message with the BrokeredMessage.GetBody<T>() method.
これらのパラメーターは Azure Functions バージョン 1.x 用です。2.x では、BrokeredMessage
の代わりに Message
を使用してください。These parameters are for Azure Functions version 1.x; for 2.x, use Message
instead of BrokeredMessage
.
JavaScript で、context.bindings.<name from function.json>
を使用して、キューまたはトピック メッセージにアクセスします。In JavaScript, access the queue or topic message by using context.bindings.<name from function.json>
. Service Bus メッセージが文字列または JSON オブジェクトとして関数に渡されます。The Service Bus message is passed into the function as either a string or JSON object.
トリガー - 有害メッセージTrigger - poison messages
Azure Functions では、有害メッセージの処理を制御することも構成することもできません。Poison message handling can't be controlled or configured in Azure Functions. Service Bus 自体で、有害なメッセージが処理されます。Service Bus handles poison messages itself.
トリガー - PeekLock 動作Trigger - PeekLock behavior
Functions ランタイムは、メッセージを PeekLock モードで受信します。The Functions runtime receives a message in PeekLock mode. それは、関数が正常に終了した場合はメッセージに対して Complete
を呼び出し、関数が失敗した場合は Abandon
を呼び出します。It calls Complete
on the message if the function finishes successfully, or calls Abandon
if the function fails. 関数が実行されている限り、関数の実行時間が PeekLock
タイムアウトよりも長くなると、ロックが自動的に更新されます。If the function runs longer than the PeekLock
timeout, the lock is automatically renewed as long as the function is running.
maxAutoRenewDuration
は host.json に構成可能です。これは OnMessageOptions.MaxAutoRenewDuration にマップされます。The maxAutoRenewDuration
is configurable in host.json, which maps to OnMessageOptions.MaxAutoRenewDuration. この設定に許可される最大値は、Service Bus のドキュメントに従って 5 分ですが、Functions の制限時間は既定の 5 分から 10 分に増やすことができます。The maximum allowed for this setting is 5 minutes according to the Service Bus documentation, whereas you can increase the Functions time limit from the default of 5 minutes to 10 minutes. Service Bus 関数の場合は、Service Bus の更新制限を超えるので増やしません。For Service Bus functions you wouldn’t want to do that then, because you’d exceed the Service Bus renewal limit.
トリガー - メッセージのメタデータTrigger - message metadata
Service Bus トリガーには、いくつかのメタデータ プロパティがあります。The Service Bus trigger provides several metadata properties. これらのプロパティは、他のバインドのバインド式の一部として、またはコードのパラメーターとして使用できます。These properties can be used as part of binding expressions in other bindings or as parameters in your code. これらは BrokeredMessage クラスのプロパティです。These are properties of the BrokeredMessage class.
プロパティProperty | 種類Type | 説明Description |
---|---|---|
DeliveryCount |
Int32 |
配信回数。The number of deliveries. |
DeadLetterSource |
string |
配信不能のソース。The dead letter source. |
ExpiresAtUtc |
DateTime |
有効期限 (UTC)。The expiration time in UTC. |
EnqueuedTimeUtc |
DateTime |
エンキューされた時刻 (UTC)。The enqueued time in UTC. |
MessageId |
string |
有効になっている場合に、重複するメッセージを識別するために Service Bus が使用できるユーザー定義の値A user-defined value that Service Bus can use to identify duplicate messages, if enabled. |
ContentType |
string |
アプリケーション固有のロジックのために送信者と受信者が利用するコンテンツ タイプ識別子。A content type identifier utilized by the sender and receiver for application specific logic. |
ReplyTo |
string |
キュー アドレスへの返信。The reply to queue address. |
SequenceNumber |
Int64 |
Service Bus によってメッセージに割り当てられる一意の番号。The unique number assigned to a message by the Service Bus. |
To |
string |
送信先アドレス。The send to address. |
Label |
string |
アプリケーション固有のラベル。The application specific label. |
CorrelationId |
string |
関連付け ID。The correlation ID. |
注意
現在、セッションで有効になっているキューやサブスクリプションで動作する Service Bus トリガーはプレビュー段階です。Currently, Service bus trigger that works with session enabled queues and subscriptions is in preview. これに関連した今後の更新については、この項目を追跡してください。Please track this item for any further updates regarding this.
この記事の前半でこれらのプロパティを使用しているコード例を参照してください。See code examples that use these properties earlier in this article.
OutputOutput
キューまたはトピック メッセージを送信するには、Azure Service Bus 出力バインドを使用します。Use Azure Service Bus output binding to send queue or topic messages.
出力 - 例Output - example
言語固有の例をご覧ください。See the language-specific example:
出力 - C# の例Output - C# example
次の例は、Service Bus キュー メッセージを送信する C# 関数を示しています。The following example shows a C# function that sends a Service Bus queue message:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string ServiceBusOutput([HttpTrigger] dynamic input, ILogger log)
{
log.LogInformation($"C# function processed: {input.Text}");
return input.Text;
}
出力 - C# スクリプトの例Output - C# script example
次の例は、function.json ファイルの Service Bus 出力バインドと、そのバインドを使用する C# スクリプト関数を示しています。The following example shows a Service Bus output binding in a function.json file and a C# script function that uses the binding. この関数は、タイマー トリガーを使用して、15 秒ごとにキュー メッセージを送信します。The function uses a timer trigger to send a queue message every 15 seconds.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
単一のメッセージを作成する C# スクリプト コードを次に示します。Here's C# script code that creates a single message:
public static void Run(TimerInfo myTimer, ILogger log, out string outputSbQueue)
{
string message = $"Service Bus queue message created at: {DateTime.Now}";
log.LogInformation(message);
outputSbQueue = message;
}
複数のメッセージを作成する C# スクリプト コードを次に示します。Here's C# script code that creates multiple messages:
public static async Task Run(TimerInfo myTimer, ILogger log, IAsyncCollector<string> outputSbQueue)
{
string message = $"Service Bus queue messages created at: {DateTime.Now}";
log.LogInformation(message);
await outputSbQueue.AddAsync("1 " + message);
await outputSbQueue.AddAsync("2 " + message);
}
出力 - F# の例Output - F# example
次の例は、function.json ファイルの Service Bus 出力バインドと、そのバインドを使用する F# スクリプト関数を示しています。The following example shows a Service Bus output binding in a function.json file and an F# script function that uses the binding. この関数は、タイマー トリガーを使用して、15 秒ごとにキュー メッセージを送信します。The function uses a timer trigger to send a queue message every 15 seconds.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
単一のメッセージを作成する F# スクリプト コードを次に示します。Here's F# script code that creates a single message:
let Run(myTimer: TimerInfo, log: ILogger, outputSbQueue: byref<string>) =
let message = sprintf "Service Bus queue message created at: %s" (DateTime.Now.ToString())
log.LogInformation(message)
outputSbQueue = message
出力 - Java の例Output - Java example
次の例は、HTTP 要求によってトリガーされたときに Service Bus キュー myqueue
にメッセージを送信する Java 関数を示しています。The following example shows a Java function that sends a message to a Service Bus queue myqueue
when triggered by a HTTP request.
@FunctionName("httpToServiceBusQueue")
@ServiceBusQueueOutput(name = "message", queueName = "myqueue", connection = "AzureServiceBusConnection")
public String pushToQueue(
@HttpTrigger(name = "request", methods = {HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS)
final String message,
@HttpOutput(name = "response") final OutputBinding<T> result ) {
result.setValue(message + " has been sent.");
return message;
}
Java 関数ランタイム ライブラリ で、その値が Service Bus キューに書き込まれる関数のパラメーターに関する @QueueOutput
注釈を使用します。In the Java functions runtime library, use the @QueueOutput
annotation on function parameters whose value would be written to a Service Bus queue. パラメーターの型は OutputBinding<T>
にする必要があります。T は POJO の Java の任意のネイティブ型です。The parameter type should be OutputBinding<T>
, where T is any native Java type of a POJO.
Java 関数は、Service Bus トピックにも書き込むことができます。Java functions can also write to a Service Bus topic. 次の例では、出力バインディングの構成を記述する@ServiceBusTopicOutput
注釈を使用します。The following example uses the @ServiceBusTopicOutput
annotation to describe the configuration for the output binding.
@FunctionName("sbtopicsend")
public HttpResponseMessage run(
@HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
@ServiceBusTopicOutput(name = "message", topicName = "mytopicname", subscriptionName = "mysubscription", connection = "ServiceBusConnection") OutputBinding<String> message,
final ExecutionContext context) {
String name = request.getBody().orElse("Azure Functions");
message.setValue(name);
return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
}
出力 - JavaScript の例Output - JavaScript example
次の例は、function.json ファイルの Service Bus 出力バインドと、そのバインドを使用する JavaScript スクリプト関数を示しています。The following example shows a Service Bus output binding in a function.json file and a JavaScript function that uses the binding. この関数は、タイマー トリガーを使用して、15 秒ごとにキュー メッセージを送信します。The function uses a timer trigger to send a queue message every 15 seconds.
function.json ファイルのバインディング データを次に示します。Here's the binding data in the function.json file:
{
"bindings": [
{
"schedule": "0/15 * * * * *",
"name": "myTimer",
"runsOnStartup": true,
"type": "timerTrigger",
"direction": "in"
},
{
"name": "outputSbQueue",
"type": "serviceBus",
"queueName": "testqueue",
"connection": "MyServiceBusConnection",
"direction": "out"
}
],
"disabled": false
}
単一のメッセージを作成する JavaScript スクリプト コードを次に示します。Here's JavaScript script code that creates a single message:
module.exports = function (context, myTimer) {
var message = 'Service Bus queue message created at ' + timeStamp;
context.log(message);
context.bindings.outputSbQueue = message;
context.done();
};
複数のメッセージを作成する JavaScript スクリプト コードを次に示します。Here's JavaScript script code that creates multiple messages:
module.exports = function (context, myTimer) {
var message = 'Service Bus queue message created at ' + timeStamp;
context.log(message);
context.bindings.outputSbQueue = [];
context.bindings.outputSbQueue.push("1 " + message);
context.bindings.outputSbQueue.push("2 " + message);
context.done();
};
出力 - Python の例Output - Python example
次の例では、Python で ServiceBus キューに書き出す方法を示します。The following example demonstrates how to write out to a ServiceBus queue in Python.
ServiceBus のバインディング定義は function.json で定義され、そこで type は serviceBus
に設定されます。A ServiceBue binding definition is defined in function.json where type is set to serviceBus
.
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "$return"
},
{
"type": "serviceBus",
"direction": "out",
"connection": "AzureServiceBusConnectionString",
"name": "msg",
"queueName": "outqueue"
}
]
}
_init_.py で、値を set
メソッドに渡すことでメッセージをキューに書き出すことができます。In _init_.py, you can write out a message to the queue by passing a value to the set
method.
import azure.functions as func
def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
input_msg = req.params.get('message')
msg.set(input_msg)
return 'OK'
出力 - 属性Output - attributes
C# クラス ライブラリでは、ServiceBusAttribute 属性を使用します。In C# class libraries, use the ServiceBusAttribute.
属性のコンストラクターは、キューの名前、またはトピックとサブスクリプションを受け取ります。The attribute's constructor takes the name of the queue or the topic and subscription. 接続のアクセス権を指定することもできます。You can also specify the connection's access rights. アクセス権の設定を選択する方法については、「出力 - 構成」セクションで説明されています。How to choose the access rights setting is explained in the Output - configuration section. 関数の戻り値に適用される属性に適用される属性を示す例は次のとおりです。Here's an example that shows the attribute applied to the return value of the function:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
...
}
次の例で示すように、Connection
プロパティを設定して、使用する Service Bus アカウントを指定できます。You can set the Connection
property to specify the Service Bus account to use, as shown in the following example:
[FunctionName("ServiceBusOutput")]
[return: ServiceBus("myqueue", Connection = "ServiceBusConnection")]
public static string Run([HttpTrigger] dynamic input, ILogger log)
{
...
}
完全な例については、「出力 - C# の例」を参照してください。For a complete example, see Output - C# example.
ServiceBusAccount
属性を使用して、クラス、メソッド、またはパラメーターのレベルで使用する Service Bus アカウントを指定できます。You can use the ServiceBusAccount
attribute to specify the Service Bus account to use at class, method, or parameter level. 詳細については、トリガー - 属性をご覧ください。For more information, see Trigger - attributes.
出力 - 構成Output - configuration
次の表は、function.json ファイルと ServiceBus
属性で設定したバインド構成のプロパティを説明しています。The following table explains the binding configuration properties that you set in the function.json file and the ServiceBus
attribute.
function.json のプロパティfunction.json property | 属性のプロパティAttribute property | 説明Description |
---|---|---|
typetype | 該当なしn/a | "serviceBus" に設定する必要があります。Must be set to "serviceBus". このプロパティは、Azure Portal でトリガーを作成するときに自動で設定されます。This property is set automatically when you create the trigger in the Azure portal. |
directiondirection | 該当なしn/a | "out" に設定する必要があります。Must be set to "out". このプロパティは、Azure Portal でトリガーを作成するときに自動で設定されます。This property is set automatically when you create the trigger in the Azure portal. |
namename | 該当なしn/a | 関数コード内のキューまたはトピックを表す変数の名前。The name of the variable that represents the queue or topic in function code. "$return" に設定して、関数の戻り値を参照します。Set to "$return" to reference the function return value. |
queueNamequeueName | QueueNameQueueName | キューの名前。Name of the queue. トピックではなくキューのメッセージを送信する場合にのみ設定します。Set only if sending queue messages, not for a topic. |
topicNametopicName | TopicNameTopicName | 監視するトピックの名前。Name of the topic to monitor. キューではなくトピックのメッセージを送信する場合にのみ設定します。Set only if sending topic messages, not for a queue. |
connectionconnection | ConnectionConnection | このバインドに使用する Service Bus 接続文字列を含むアプリ設定の名前です。The name of an app setting that contains the Service Bus connection string to use for this binding. アプリ設定の名前が "AzureWebJobs" で始まる場合は、名前の残りの部分のみを指定できます。If the app setting name begins with "AzureWebJobs", you can specify only the remainder of the name. たとえば、connection を "MyServiceBus" に設定した場合、Functions ランタイムは "AzureWebJobsMyServiceBus" という名前のアプリ設定を探します。For example, if you set connection to "MyServiceBus", the Functions runtime looks for an app setting that is named "AzureWebJobsMyServiceBus." connection を空のままにした場合、Functions ランタイムは、アプリ設定内の "AzureWebJobsServiceBus" という名前の既定の Service Bus 接続文字列を使用します。If you leave connection empty, the Functions runtime uses the default Service Bus connection string in the app setting that is named "AzureWebJobsServiceBus".接続文字列は、管理資格情報の取得に関する記事の手順に従って取得します。To obtain a connection string, follow the steps shown at Get the management credentials. 接続文字列は、特定のキューまたはトピックに限らず、Service Bus 名前空間のものである必要があります。The connection string must be for a Service Bus namespace, not limited to a specific queue or topic. |
accessRightsaccessRights | Access (アクセス)Access | 接続文字列のアクセス権。Access rights for the connection string. 使用できる値は manage と listen です。Available values are manage and listen . 既定値は manage で、connection が管理アクセス許可を持つことを示します。The default is manage , which indicates that the connection has the Manage permission. 管理アクセス許可を持たない接続文字列を使用する場合は、accessRights を "listen" に設定します。If you use a connection string that does not have the Manage permission, set accessRights to "listen". 設定しないと、Functions ランタイムが管理権限を必要とする操作の試行に失敗する可能性があります。Otherwise, the Functions runtime might fail trying to do operations that require manage rights. 最新バージョンの Storage SDK が管理の操作をサポートしていないため、Azure Functions バージョン 2.x ではこのプロパティを利用できません。In Azure Functions version 2.x, this property is not available because the latest version of the Storage SDK doesn't support manage operations. |
ローカルで開発している場合、アプリ設定は local.settings.json ファイルに保存されます。When you're developing locally, app settings go into the local.settings.json file.
出力 - 使用方法Output - usage
Azure Functions 1.x では、キューが存在しない場合に accessRights
を manage
に設定していると、ランタイムによってキューが作成されます。In Azure Functions 1.x, the runtime creates the queue if it doesn't exist and you have set accessRights
to manage
. Azure Functions バージョン 2.x では、キューまたはトピックが既に存在する必要があります。存在しないキューまたはトピックを指定した場合、関数は失敗します。In Functions version 2.x, the queue or topic must already exist; if you specify a queue or topic that doesn't exist, the function will fail.
C# とC# スクリプトでは、出力バインドに次のパラメーター型を使用できます。In C# and C# script, you can use the following parameter types for the output binding:
out T paramName
-T
は任意の JSON シリアル化可能な型にすることができます。out T paramName
-T
can be any JSON-serializable type. 関数が終了したときにこのパラメーターの値が null の場合、Functions は、null オブジェクトでメッセージを作成します。If the parameter value is null when the function exits, Functions creates the message with a null object.out string
- 関数が終了したときにパラメーター値が null の場合、Functions はメッセージを作成しません。out string
- If the parameter value is null when the function exits, Functions does not create a message.out byte[]
- 関数が終了したときにパラメーター値が null の場合、Functions はメッセージを作成しません。out byte[]
- If the parameter value is null when the function exits, Functions does not create a message.out BrokeredMessage
- 関数が終了したときにパラメーター値が null の場合、Functions はメッセージを作成しません (Functions 1.x の場合)。out BrokeredMessage
- If the parameter value is null when the function exits, Functions does not create a message (for Functions 1.x)out Message
- 関数が終了したときにパラメーター値が null の場合、Functions はメッセージを作成しません (Functions 2.x の場合)。out Message
- If the parameter value is null when the function exits, Functions does not create a message (for Functions 2.x)ICollector<T>
またはIAsyncCollector<T>
- 複数のメッセージを作成する場合。ICollector<T>
orIAsyncCollector<T>
- For creating multiple messages.Add
メソッドを呼び出すときに、メッセージが作成されます。A message is created when you call theAdd
method.
C# 関数を使用する場合:When working with C# functions:
非同期関数には、
out
パラメーターの代わりに戻り値またはIAsyncCollector
が必要です。Async functions need a return value orIAsyncCollector
instead of anout
parameter.セッション ID にアクセスするには、
Message
型にバインドし、sessionId
プロパティを使用します。To access the session ID, bind to aMessage
type and use thesessionId
property.
JavaScript で、context.bindings.<name from function.json>
を使用して、キューまたはトピックにアクセスします。In JavaScript, access the queue or topic by using context.bindings.<name from function.json>
. 文字列、バイト配列、または (JSON に逆シリアル化された) JavaScript オブジェクトを context.binding.<name>
に割り当てることができます。You can assign a string, a byte array, or a JavaScript object (deserialized into JSON) to context.binding.<name>
.
C# 以外の言語で、セッションが有効なキューにメッセージを送信するには、組み込みの出力バインドではなく、Azure Service Bus SDK を使用します。To send a message to a session-enabled queue in non-C# languages, use the Azure Service Bus SDK rather than the built-in output binding.
例外とリターン コードExceptions and return codes
バインドBinding | リファレンスReference |
---|---|
Service BusService Bus | Service Bus のエラー コードService Bus Error Codes |
Service BusService Bus | Service Bus の制限Service Bus Limits |
host.json 設定host.json settings
このセクションでは、バージョン 2.x でこのバインディングに使用可能なグローバル構成設定について説明します。This section describes the global configuration settings available for this binding in version 2.x. 次の host.json ファイルの例には、このバインディングのバージョン 2.x の設定のみが含まれています。The example host.json file below contains only the version 2.x settings for this binding. バージョン 2.x でのグローバル構成設定の詳細については、Azure Functions バージョン 2.x の host.json のリファレンスを参照してください。For more information about global configuration settings in version 2.x, see host.json reference for Azure Functions version 2.x.
注意
Functions 1.x の host.json のリファレンスについては、「host.json reference for Azure Functions 1.x (Azure Functions 1.x の host.json のリファレンス)」を参照してください。For a reference of host.json in Functions 1.x, see host.json reference for Azure Functions 1.x.
{
"version": "2.0",
"extensions": {
"serviceBus": {
"prefetchCount": 100,
"messageHandlerOptions": {
"autoComplete": false,
"maxConcurrentCalls": 32,
"maxAutoRenewDuration": "00:55:00"
}
}
}
}
プロパティProperty | DefaultDefault | 説明Description |
---|---|---|
maxAutoRenewDurationmaxAutoRenewDuration | 00:05:0000:05:00 | メッセージ ロックが自動的に更新される最大間隔。The maximum duration within which the message lock will be renewed automatically. |
autoCompleteautoComplete | truetrue | トリガーをすぐに完了としてマークする (オートコンプリート) か、呼び出しの処理が完了するまで待機するか。Whether the trigger should immediately mark as complete (autocomplete) or wait for processing to call complete. |
maxConcurrentCallsmaxConcurrentCalls | 1616 | メッセージ ポンプが開始する必要があるコールバックの同時呼び出しの最大数The maximum number of concurrent calls to the callback that the message pump should initiate. 既定では、Functions ランタイムは、複数のメッセージを同時に処理します。By default, the Functions runtime processes multiple messages concurrently. 一度に 1 つのキューまたはトピックのメッセージのみを処理するようにランタイムに指示するには、maxConcurrentCalls を 1 に設定します。To direct the runtime to process only a single queue or topic message at a time, set maxConcurrentCalls to 1. |
prefetchCountprefetchCount | 該当なしn/a | 基になる MessageReceiver に使用される既定の PrefetchCount。The default PrefetchCount that will be used by the underlying MessageReceiver. |
次の手順Next steps
フィードバック
フィードバックを読み込んでいます...