Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Tutorial: Create a serverless notification app with Azure Functions and Azure Web PubSub service

Feedback

In this article

The Azure Web PubSub service helps you build real-time messaging web applications using WebSockets. Azure Functions is a serverless platform that lets you run your code without managing any infrastructure. In this tutorial, you learn how to use Azure Web PubSub service and Azure Functions to build a serverless application with real-time messaging under notification scenarios.

In this tutorial, you learn how to:

  • Build a serverless notification app
  • Work with Web PubSub function input and output bindings
  • Run the sample functions locally
  • Deploy the function to Azure Function App

Important

Raw connection strings appear in this article for demonstration purposes only.

A connection string includes the authorization information required for your application to access Azure Web PubSub service. The access key inside the connection string is similar to a root password for your service. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely andsecure your connection withWebPubSubServiceClient.

Avoid distributing access keys to other users, hard-coding them, or saving them anywhere in plain text that is accessible to others. Rotate your keys if you believe they may have been compromised.

Prerequisites

If you don't have an Azure account, create afree account before you begin.

Sign in to Azure

Sign in to the Azure portal athttps://portal.azure.com/ with your Azure account.

Create an Azure Web PubSub service instance

Your application will connect to a Web PubSub service instance in Azure.

  1. Select the New button found on the upper left-hand corner of the Azure portal. In the New screen, typeWeb PubSub in the search box and press enter. (You could also search the Azure Web PubSub from theWeb category.)

    Screenshot of searching the Azure Web PubSub in portal.

  2. SelectWeb PubSub from the search results, then selectCreate.

  3. Enter the following settings.

    SettingSuggested valueDescription
    Resource nameGlobally unique nameThe globally unique Name that identifies your new Web PubSub service instance. Valid characters area-z,A-Z,0-9, and-.
    SubscriptionYour subscriptionThe Azure subscription under which this new Web PubSub service instance is created.
    Resource GroupmyResourceGroupName for the new resource group in which to create your Web PubSub service instance.
    LocationWest USChoose aregion near you.
    Pricing tierFreeYou can first try Azure Web PubSub service for free. Learn more details aboutAzure Web PubSub service pricing tiers
    Unit count-Unit count specifies how many connections your Web PubSub service instance can accept. Each unit supports 1,000 concurrent connections at most. It is only configurable in the Standard tier.

    Screenshot of creating the Azure Web PubSub instance in portal.

  4. SelectCreate to start deploying the Web PubSub service instance.

Create and run the functions locally

  1. Make sure you haveAzure Functions Core Tools installed. Now, create an empty directory for the project. Run command under this working directory. Use one of the given options below.

    func init --worker-runtime javascript --model V4
  2. Follow the steps to installMicrosoft.Azure.WebJobs.Extensions.WebPubSub.

    Confirm or updatehost.json's extensionBundle to version4.* or later to get Web PubSub support. For updating thehost.json, open the file in editor, and then replace the existing version extensionBundle to version4.* or later.

    {    "extensionBundle": {        "id": "Microsoft.Azure.Functions.ExtensionBundle",        "version": "[4.*, 5.0.0)"    }}
  3. Create anindex function to read and host a static web page for clients.

    func new -n index -t HttpTrigger
    • Updatesrc/functions/index.js and copy following codes.
      const { app } = require('@azure/functions');const { readFile } = require('fs/promises');app.http('index', {    methods: ['GET', 'POST'],    authLevel: 'anonymous',    handler: async (context) => {        const content = await readFile('index.html', 'utf8', (err, data) => {            if (err) {                context.err(err)                return            }        });        return {             status: 200,            headers: {                 'Content-Type': 'text/html'            },             body: content,         };    }});
  4. Create anegotiate function to help clients get service connection url with access token.

    func new -n negotiate -t HttpTrigger
    • Updatesrc/functions/negotiate.js and copy following codes.
      const { app, input } = require('@azure/functions');const connection = input.generic({    type: 'webPubSubConnection',    name: 'connection',    hub: 'notification'});app.http('negotiate', {    methods: ['GET', 'POST'],    authLevel: 'anonymous',    extraInputs: [connection],    handler: async (request, context) => {        return { body: JSON.stringify(context.extraInputs.get('connection')) };    },});
  5. Create anotification function to generate notifications withTimerTrigger.

    func new -n notification -t TimerTrigger
    • Updatesrc/functions/notification.js and copy following codes.
      const { app, output } = require('@azure/functions');const wpsAction = output.generic({    type: 'webPubSub',    name: 'action',    hub: 'notification'});app.timer('notification', {    schedule: "*/10 * * * * *",    extraOutputs: [wpsAction],    handler: (myTimer, context) => {        context.extraOutputs.set(wpsAction, {            actionName: 'sendToAll',            data: `[DateTime: ${new Date()}] Temperature: ${getValue(22, 1)}\xB0C, Humidity: ${getValue(40, 2)}%`,            dataType: 'text',        });    },});function getValue(baseNum, floatNum) {    return (baseNum + 2 * floatNum * (Math.random() - 0.5)).toFixed(3);}
  6. Add the client single pageindex.html in the project root folder and copy content.

    <html>    <body>    <h1>Azure Web PubSub Notification</h1>    <div></div>    <script>        (async function () {            let messages = document.querySelector('#messages');            let res = await fetch(`${window.location.origin}/api/negotiate`);            let url = await res.json();            let ws = new WebSocket(url.url);            ws.onopen = () => console.log('connected');            ws.onmessage = event => {                let m = document.createElement('p');                m.innerText = event.data;                messages.appendChild(m);            };        })();    </script>    </body></html>
  7. Configure and run the Azure Function app

    Raw connection strings appear in this article for demonstration purposes only. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely andsecure your connection withWebPubSubServiceClient.

    • In the browser, open theAzure portal and confirm the Web PubSub Service instance you deployed earlier was successfully created. Navigate to the instance.
    • SelectKeys and copy out the connection string.

    Screenshot of copying the Web PubSub connection string.

    Run command in the function folder to set the service connection string. Replace<connection-string> with your value as needed.

    func settings add WebPubSubConnectionString "<connection-string>"

    Note

    TimerTrigger used in the sample has dependency on Azure Storage, but you can use local storage emulator when the Function is running locally. If you got some error likeThere was an error performing a read operation on the Blob Storage Secret Repository. Please ensure the 'AzureWebJobsStorage' connection string is valid., you'll need to download and enableStorage Emulator.

    Now you're able to run your local function by command.

    func start --port 7071

    And checking the running logs, you can visit your local host static page by visiting:http://localhost:7071/api/index.

    Note

    Some browsers automatically redirect tohttps that leads to wrong url. Suggest to useEdge and double check the url if rendering is not success.

Deploy Function App to Azure

Before you can deploy your function code to Azure, you need to create three resources:

  • A resource group, which is a logical container for related resources.
  • A storage account, which is used to maintain state and other information about your functions.
  • A function app, which provides the environment for executing your function code. A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment and sharing of resources.

Use the following commands to create these items.

  1. Sign in to Azure:

    az login
  2. Create a resource group or you can skip by reusing the one of Azure Web PubSub service:

    az group create -n WebPubSubFunction -l <REGION>
  3. Create a general-purpose storage account in your resource group and region:

    az storage account create -n <STORAGE_NAME> -l <REGION> -g WebPubSubFunction
  4. Create the function app in Azure:

    az functionapp create --resource-group WebPubSubFunction --consumption-plan-location <REGION> --runtime node --runtime-version 18 --functions-version 4 --name <FUNCIONAPP_NAME> --storage-account <STORAGE_NAME>

    Note

    CheckAzure Functions runtime versions documentation to set--runtime-version parameter to supported value.

  5. Deploy the function project to Azure:

    Once you create your function app in Azure, you're now ready to deploy your local functions project by using thefunc azure functionapp publish command.

    func azure functionapp publish <FUNCIONAPP_NAME> --publish-local-settings

    Note

    Here we are deploying local settingslocal.settings.json together with command parameter--publish-local-settings. If you're using Microsoft Azure Storage Emulator, you can typeno to skip overwriting this value on Azure following the prompt message:App setting AzureWebJobsStorage is different between azure and local.settings.json, Would you like to overwrite value in azure? [yes/no/show]. Besides, you can update Function App settings inAzure Portal ->Settings ->Configuration.

  6. Now you can check your site from Azure Function App by navigating to URL:https://<FUNCIONAPP_NAME>.azurewebsites.net/api/index.

Clean up resources

If you're not going to continue to use this app, delete all resources created by this doc with the following steps so you don't incur any charges:

  1. In the Azure portal, selectResource groups on the far left, and then select the resource group you created. Use the search box to find the resource group by its name instead.

  2. In the window that opens, select the resource group, and then selectDelete resource group.

  3. In the new window, type the name of the resource group to delete, and then selectDelete.

Next steps

In this quickstart, you learned how to run a serverless chat application. Now, you could start to build your own application.


Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?