【发布时间】:2016-07-07 15:48:14
【问题描述】:
我有一个从服务器获取 api 数据的异步方法。当我在本地机器上的控制台应用程序中运行此代码时,它以高速执行,每分钟在异步函数中推送数百个 http 调用。然而,当我将相同的代码从 Azure WebJob 队列消息中触发时,它似乎同步运行并且我的数字爬行 - 我确信我在我的方法中遗漏了一些简单的东西 - 感谢任何帮助。
(1) .. WebJob 函数,用于侦听队列中的消息并在收到消息时启动 api 获取过程:
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
public static async Task ProcessQueueMessage ([QueueTrigger("myqueue")] string message, TextWriter log)
{
var getAPIData = new GetData();
getAPIData.DoIt(message).Wait();
log.WriteLine("*** done: " + message);
}
}
(2) azure 之外的类在异步模式下高速工作...
class GetData
{
// wrapper that is called by the message function trigger
public async Task DoIt(string MessageFile)
{
await CallAPI(MessageFile);
}
public async Task<string> CallAPI(string MessageFile)
{
/// create a list of sample APIs to call...
var apiCallList = new List<string>();
apiCallList.Add("localhost/?q=1");
apiCallList.Add("localhost/?q=2");
apiCallList.Add("localhost/?q=3");
apiCallList.Add("localhost/?q=4");
apiCallList.Add("localhost/?q=5");
// setup httpclient
HttpClient client =
new HttpClient() { MaxResponseContentBufferSize = 10000000 };
var timeout = new TimeSpan(0, 5, 0); // 5 min timeout
client.Timeout = timeout;
// create a list of http api get Task...
IEnumerable<Task<string>> allResults = apiCallList.Select(str => ProcessURLPageAsync(str, client));
// wait for them all to complete, then move on...
await Task.WhenAll(allResults);
return allResults.ToString();
}
async Task<string> ProcessURLPageAsync(string APIAddressString, HttpClient client)
{
string page = "";
HttpResponseMessage resX;
try
{
// set the address to call
Uri URL = new Uri(APIAddressString);
// execute the call
resX = await client.GetAsync(URL);
page = await resX.Content.ReadAsStringAsync();
string rslt = page;
// do something with the api response data
}
catch (Exception ex)
{
// log error
}
return page;
}
}
【问题讨论】:
-
您是否尝试过更改“getAPIData.DoIt(message).Wait();”到“等待 getAPIData.DoIt(message);”?
-
感谢 Jason - 你和其他人在这里帮助我完成这项工作。非常感谢。
标签: azure azure-storage azure-webjobs