问题描述
我的Web应用程序部署在Azure中,并在Asp.Net Core中实现。我想根据cpu /内存/网络使用百分比来限制请求。例如,当cpu使用率超过90%时,限制组件将限制50%的请求。
最大的问题是:
解决方法
据我所知,azure WebApp是sandbox,我们没有足够的权限来访问Azure Web应用程序的辅助服务器的指标。
该用户帐户必须是Windows中Administrators组的成员或Performance Monitor Users组的成员。
这是一个解决方法,我们可以使应用程序Insight做到这一点。我们需要为Azure WebApp配置Application Insight。详细信息,您可以参考此doc。
我们可以使用Application Insight rest api获取当前Web应用程序的指标,例如进程cpu的使用情况。 API Document。
我们可以在Application Insight门户中获取应用程序ID和api密钥,如下图所示:
详细信息,您可以参考此article。
然后,您可以使用以下代码将请求发送到Application Insight API,以获取当前的CPU使用情况。
public static string GetTelemetry(string appid,string apikey)
{
string Url = "https://api.applicationinsights.io/v1/apps/{0}/metrics/performanceCounters/processCpuPercentage";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-key",apikey);
var req = string.Format(Url,appid);
HttpResponseMessage response = client.GetAsync(req).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
else
{
return response.ReasonPhrase;
}
}
结果: