LoginSignup
0
0

More than 3 years have passed since last update.

[Azure Functions] 一定確率で少し待ってから応答を返す関数 (C#)

Posted at

はじめに

LBの動作やアプリ側の挙動確認のため、一定の確率で応答に時間をかけてから返すサービスを作っておきたいなー…と思いたち、Azure Functions で簡単に作ってみました。

環境

  • .NET Core 3.1

コード

Visual Studio 2019 のテンプレートから HTTP Trigger で作成。

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Random10SecFunction01
{
    public static class Function1
    {
        [FunctionName("Random10SecFunction01")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            int WAIT_TIME = 10; // seconds
            Random rnd = new Random(Environment.TickCount);

            if (rnd.Next(0,99) < 10)
            {
                log.LogInformation("Wait...");
                await Task.Delay(WAIT_TIME * 1000);
            }

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);

            string responseMessage = "This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

Usage

下記のようにアクセスすると、既定では90%の確率で即時応答、10%の確率で10秒間待ってレスポンスを返します。

<URL>/Random10SecFunction01
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0