Azure Functions에 대한 Azure Notification Hubs 출력 바인딩

이 문서에서는 Azure Functions에서 Azure Notification Hubs 바인딩을 사용하여 푸시 알림을 보내는 방법을 설명합니다. Azure Functions는 Notification Hub의 출력 바인딩을 지원합니다.

사용하려는 PNS(플랫폼 알림 서비스)에 대해 Notification Hubs를 구성해야 합니다. Notification Hubs에서 클라이언트 앱에서 푸시 알림을 가져오는 방법에 대한 자세한 내용은 빠른 시작: 알림 허브에서 푸시 알림 설정을 참조하세요.

Important

Google은 FCM(Firebase Cloud Messaging)을 위해 GCM(Google Cloud Messaging)을 더 이상 사용하지 않습니다. 그러나 Notification Hubs에 대한 출력 바인딩은 FCM을 지원하지 않습니다. FCM을 사용하여 알림을 보내려면 함수에서 직접 Firebase API를 사용하거나 템플릿 알림을 사용합니다.

패키지: Functions 1.x

Notification Hubs 바인딩은 Microsoft.Azure.WebJobs.Extensions.NotificationHubs NuGet 패키지 버전 1.x에서 제공됩니다. 패키지의 소스 코드는 azure-webjobs-sdk-extensions GitHub 리포지토리에 있습니다.

다음 표에서는 각 개발 환경에서 출력 바인딩에 대한 지원을 추가하는 방법을 나열합니다.

개발 환경 Functions 1.x에서 지원을 추가하려면
로컬 개발: C# 클래스 라이브러리 패키지 설치
로컬 개발: C# 스크립트, JavaScript, F# 자동
포털 개발 자동

패키지: Functions 2.x 이상

출력 바인딩은 Functions 2.x 이상에서 사용할 수 없습니다.

예제: 템플릿

보내는 알림은 네이티브 알림 또는 템플릿 알림일 수 있습니다. 네이티브 알림은 출력 바인딩의 속성에 platform 구성된 대로 특정 클라이언트 플랫폼을 대상으로 합니다. 템플릿 알림은 여러 플랫폼을 대상으로 하는 데 사용할 수 있습니다.

각 언어에 대한 템플릿 예제:

C# 스크립트 템플릿 예제: out 매개 변수

이 예제에서는 템플릿에 자리 표시자가 포함된 message 템플릿 등록에 대한 알림을 보냅니다.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static void Run(string myQueueItem,  out IDictionary<string, string> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = GetTemplateProperties(myQueueItem);
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return templateProperties;
}

C# 스크립트 템플릿 예제: 비동기

비동기 코드를 사용하는 경우 out 매개 변수는 허용되지 않습니다. 이 경우 템플릿 알림을 반환하는 데 사용합니다 IAsyncCollector . 다음 코드는 이전 예제의 비동기 예제입니다.

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public static async Task Run(string myQueueItem, IAsyncCollector<IDictionary<string,string>> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    log.Info($"Sending Template Notification to Notification Hub");
    await notification.AddAsync(GetTemplateProperties(myQueueItem));    
}

private static IDictionary<string, string> GetTemplateProperties(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["user"] = "A new user wants to be added : " + message;
    return templateProperties;
}

C# 스크립트 템플릿 예제: JSON

이 예제에서는 유효한 JSON 문자열을 사용하여 템플릿에 자리 표시자가 포함된 message 템플릿 등록에 대한 알림을 보냅니다.

using System;

public static void Run(string myQueueItem,  out string notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");
    notification = "{\"message\":\"Hello from C#. Processed a queue item!\"}";
}

C# 스크립트 템플릿 예제: 라이브러리 형식

이 예제에서는 Microsoft Azure Notification Hubs 라이브러리에 정의된 형식을 사용하는 방법을 보여 줍니다.

#r "Microsoft.Azure.NotificationHubs"

using System;
using System.Threading.Tasks;
using Microsoft.Azure.NotificationHubs;

public static void Run(string myQueueItem,  out Notification notification, TraceWriter log)
{
   log.Info($"C# Queue trigger function processed: {myQueueItem}");
   notification = GetTemplateNotification(myQueueItem);
}

private static TemplateNotification GetTemplateNotification(string message)
{
    Dictionary<string, string> templateProperties = new Dictionary<string, string>();
    templateProperties["message"] = message;
    return new TemplateNotification(templateProperties);
}

F# 템플릿 예제

이 예제에서는 다음을 포함하는 템플릿 등록대한 알림을 보냅니다.messagelocation

let Run(myTimer: TimerInfo, notification: byref<IDictionary<string, string>>) =
    notification = dict [("location", "Redmond"); ("message", "Hello from F#!")]

JavaScript 템플릿 예제

이 예제에서는 다음을 포함하는 템플릿 등록대한 알림을 보냅니다.messagelocation

module.exports = async function (context, myTimer) {
    var timeStamp = new Date().toISOString();

    if (myTimer.IsPastDue)
    {
        context.log('Node.js is running late!');
    }
    context.log('Node.js timer trigger function ran!', timeStamp);  
    context.bindings.notification = {
        location: "Redmond",
        message: "Hello from Node!"
    };
};

예: APNS 네이티브

이 C# 스크립트 예제에서는 네이티브 APNS(Apple Push Notification Service) 알림을 보내는 방법을 보여 줍니다.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example, the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The JSON format for a native Apple Push Notification Service (APNS) notification is:
    // { "aps": { "alert": "notification message" }}  

    log.LogInformation($"Sending APNS notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string apnsNotificationPayload = "{\"aps\": {\"alert\": \"A new user wants to be added (" + 
                                        user.name + ")\" }}";
    log.LogInformation($"{apnsNotificationPayload}");
    await notification.AddAsync(new AppleNotification(apnsNotificationPayload));        
}

예: WNS 네이티브

이 C# 스크립트 예제에서는 Microsoft Azure Notification Hubs 라이브러리정의된 형식을 사용하여 네이티브 WNS(Windows 푸시 알림 서비스) 알림 메시지를 보내는 방법을 보여 줍니다.

#r "Microsoft.Azure.NotificationHubs"
#r "Newtonsoft.Json"

using System;
using Microsoft.Azure.NotificationHubs;
using Newtonsoft.Json;

public static async Task Run(string myQueueItem, IAsyncCollector<Notification> notification, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed: {myQueueItem}");

    // In this example, the queue item is a new user to be processed in the form of a JSON string with 
    // a "name" value.
    //
    // The XML format for a native WNS toast notification is ...
    // <?xml version="1.0" encoding="utf-8"?>
    // <toast>
    //      <visual>
    //     <binding template="ToastText01">
    //       <text id="1">notification message</text>
    //     </binding>
    //   </visual>
    // </toast>

    log.Info($"Sending WNS toast notification of a new user");    
    dynamic user = JsonConvert.DeserializeObject(myQueueItem);    
    string wnsNotificationPayload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<toast><visual><binding template=\"ToastText01\">" +
                                        "<text id=\"1\">" + 
                                            "A new user wants to be added (" + user.name + ")" + 
                                        "</text>" +
                                    "</binding></visual></toast>";

    log.Info($"{wnsNotificationPayload}");
    await notification.AddAsync(new WindowsNotification(wnsNotificationPayload));        
}

특성

C# 클래스 라이브러리에서 NotificationHub 특성을 사용합니다.

특성의 생성자 매개 변수 및 속성은 구성 섹션에 설명되어 있습니다.

구성

다음 표에서는 function.json 파일 및 특성에 설정한 바인딩 구성 속성을 나열합니다NotificationHub.

function.json 속성 특성 속성 설명
type 해당 없음 notificationHub로 설정합니다.
direction 해당 없음 out로 설정합니다.
이름 해당 없음 알림 허브 메시지의 함수 코드에 사용되는 변수 이름입니다.
tagExpression TagExpression 태그 식을 사용하면 태그 식과 일치하는 알림을 수신하도록 등록된 디바이스 집합에 알림을 배달하도록 지정할 수 있습니다. 자세한 내용은 라우팅 및 태그 식을 참조 하세요.
hubName HubName Azure Portal의 알림 허브 리소스 이름입니다.
connection ConnectionStringSetting Notification Hubs 연결 문자열 포함하는 앱 설정의 이름입니다. 연결 문자열 알림 허브의 DefaultFullSharedAccessSignature 값으로 설정합니다. 자세한 내용은 연결 문자열 설정을 참조 하세요.
platform 플랫폼 플랫폼 속성은 알림이 대상으로 하는 클라이언트 플랫폼을 나타냅니다. 기본적으로 출력 바인딩에서 platform 속성을 생략하면 템플릿 알림을 사용하여 Azure Notification Hub에 구성된 플랫폼을 대상으로 지정할 수 있습니다. 템플릿을 사용하여 Azure Notification Hub에서 플랫폼 간 알림을 보내는 방법에 대한 자세한 내용은 Notification Hubs 템플릿을 참조 하세요. 플랫폼이 설정되면 다음 값 중 하나여야 합니다.

로컬에서 개발하는 경우 Values 컬렉션의 local.settings.json 파일에 애플리케이션 설정을 추가합니다.

function.json 파일 예제

다음은 function.json 파일의 Notification Hubs 바인딩 예제입니다.

{
  "bindings": [
    {
      "type": "notificationHub",
      "direction": "out",
      "name": "notification",
      "tagExpression": "",
      "hubName": "my-notification-hub",
      "connection": "MyHubConnectionString",
      "platform": "apns"
    }
  ],
  "disabled": false
}

연결 문자열 설정

알림 허브 출력 바인딩을 사용하려면 허브에 대한 연결 문자열을 구성해야 합니다. Azure Portal의 통합 탭에서 기존 알림 허브를 선택하거나 새 알림 허브를 만들 수 있습니다. 연결 문자열을 수동으로 구성할 수도 있습니다.

기존 알림 허브에 대한 연결 문자열 구성하려면 다음을 수행합니다.

  1. Azure Portal에서 알림 허브로 이동하여 액세스 정책을 선택하고 DefaultFullSharedAccessSignature 정책 옆에 있는 복사 단추를 선택합니다.

    DefaultFullSharedAccessSignature 정책에 대한 연결 문자열 알림 허브에 복사됩니다. 이 연결 문자열 함수에서 허브로 알림 메시지를 보낼 수 있습니다. 알림 허브 연결 문자열 복사하는 방법을 보여 주는 스크린샷

  2. Azure Portal에서 함수 앱으로 이동하고 설정을 확장한 다음 환경 변수를 선택합니다.

  3. 앱 설정 탭에서 + 추가를 선택하여 MyHubConnectionString과 같은 키를 추가합니다. 이 앱 설정의 이름은 function.json 또는 .NET 특성의 출력 바인딩 연결 설정입니다. 자세한 내용은 구성을 참고하시기 바랍니다.

  4. 값에 대해 알림 허브에서 복사한 DefaultFullSharedAccessSignature 연결 문자열 붙여넣은 다음 적용을 선택합니다.

로컬에서 개발하는 경우 Values 컬렉션의 local.settings.json 파일에 애플리케이션 설정을 추가합니다.

예외 및 반환 코드

바인딩 참조
알림 허브 작업 가이드