【发布时间】:2013-08-14 14:47:35
【问题描述】:
我有一个 WebApi,它为每个传入请求调用 2 个单独的 Web 服务,执行一些后期处理并返回结果。
第一个 webservice 调用在本地缓存 1 小时,其中的数据决定了对第二个 webservice 的查询。对每个传入请求调用第二个 Web 服务。在发出第二个请求后,每个结果都会使用业务逻辑进行处理并返回给客户端响应。
对第二个 Web 服务的调用不能是异步的,因为它使用了不允许 await 关键字的第 3 方 dll。我所做的是将第二个 web 服务调用和后处理封装到一个异步函数中,该函数从控制器调用。
// /api/controller/news?key=a&state=b
public async Task<HttpResponseMessage> GetNews(string key, string state)
{
// call to first webservice if not in cache
if (JsonConfig != null && JsonConfig.Configuration.NewsQuery.ContainsKey(key))
{
var results = await SearchProxyProvider.Search(filters.All, filters.Any, filters.None, filters.Sort, 100, 0, true, state, true);
int totalCount = results.TotalCount;
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
// Helper class method
public async Task<ItemCollection<Item>> Search(List<FieldValuePair> allFilters, List<FieldValuePair> anyFilters, List<FieldValuePair> noneFilters, SortedFieldDictionary sortBy, int pageSize = 100, int pageNumber = 0, bool exact = true, string stateFilter = null, bool getAllResults = true)
{
// call to 2nd api
search = SomeApi.Search(allFilters, anyFilters, noneFilters, pageSize, pageNumber, exact,
sortBy, null, WebApiConstant.Settings.CustomFields, true);
// post processing on search results
return search;
}
因为对第一个 Web 服务的调用被缓存在本地,所以我并不认为将其设为异步有很大的好处。
我只是想看看这种方法是完全错误还是正确。
【问题讨论】:
-
您预计平均每小时会调用多少次 Web api?
-
查看 1000 个并发用户。会有多台服务器对webapi进行负载均衡,2-3。预计初始应用下载量为 40 万用户。
标签: c# asp.net-mvc-4 asp.net-web-api .net-4.5 async-await