如何确保在首次请求之前“预热” API?

时间:2019-03-06 09:10:31

标签: .net-core xamarin.android kestrel

我有一个xamarin android应用,它向.net核心(在Windows Server的IIS上)托管的api发出请求。初始请求总是要花很长时间加载(可能是由于某些预热过程)。如何确保在用户需要发出请求时API已准备就绪?

我是否仅在应用启动时发出快速异步获取/发布请求?这似乎效率不高...

1 个答案:

答案 0 :(得分:2)

您需要对API使用运行状况检查:

public class ExampleHealthCheck : IHealthCheck
{
    public ExampleHealthCheck()
    {
        // Use dependency injection (DI) to supply any required services to the
        // "warmed up" check.
    }

    public Task<HealthCheckResult> CheckHealthAsync(
    HealthCheckContext context, 
         CancellationToken cancellationToken = default(CancellationToken))
    {
        // Execute "warmed up" check logic here.

        var healthCheckResultHealthy = true;

        if (healthCheckResultHealthy)
        {
            return Task.FromResult(
            HealthCheckResult.Healthy("The check indicates a healthy result."));
        }

        return Task.FromResult(
        HealthCheckResult.Unhealthy("The check indicates an unhealthy result."));
    }
}

将您的服务添加到健康检查服务中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHealthChecks()
        .AddCheck<ExampleHealthCheck>("example_health_check");
}

在Startup.Configure中,使用端点URL在处理管道中调用UseHealthChecks:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHealthChecks("/health");
}

文档链接:https://docs.microsoft.com/ru-ru/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-2.2