处理web api中的多个类似请求

时间:2015-03-19 15:19:47

标签: c# asp.net-mvc asp.net-web-api instagram

在我的WebApi控制器中,我有以下(伪)代码从Instagrams real-time API接收更新通知:

[HttpPost]
public void Post(InstagramUpdate instagramUpdate)
{
    var subscriptionId = instagramUpdate.SubscriptionId;
    var lastUpdate = GetLastUpdate(subscriptionId);

    // To avoid breaking my Instagram request limit, do not fetch new images too often.
    if (lastUpdate.AddSeconds(5) < DateTime.UtcNow)
    {
        // More than 5 seconds ago since last update for this subscription. Get new images
        GetNewImagesFromInstagram(subscriptionId);
        UpdateLastUpdate(subscriptionId, DateTime.UtcNow);
    }
}

如果我几乎同时收到同一订阅的两个更新通知,这将无法正常工作,因为lastUpdate在第一个请求处理完之后才会更新。

解决这个问题的最佳方法是什么?我正在考虑使用某种缓存,但我不确定如何。对于这些事情,是否有某种最佳实践?我猜这是一个常见问题:“接收通知,如果最近没有做某事就做点什么......”

2 个答案:

答案 0 :(得分:1)

感谢this answer我使用MemoryCache

采用了以下方法
[HttpPost]
public void Post(IEnumerable<InstagramUpdate> instagramUpdates)
{
    foreach (var instagramUpdate in instagramUpdates)
    {
        if (WaitingToProcessSubscriptionUpdate(instagramUpdate.Subscription_id))
        {
            // Ongoing request, do nothing
        }
        else
        {
            // Process update
        }
    }
}

private bool WaitingToProcessSubscriptionUpdate(string subscriptionId)
{
    // Check in the in memory cache if this subscription is in queue to be processed. Add it otherwise
    var queuedRequest = _cache.AddOrGetExisting(subscriptionId, string.Empty, new CacheItemPolicy
    {
        // Automatically expire this item after 1 minute (if update failed for example)
        AbsoluteExpiration = DateTime.Now.AddMinutes(1)
    });

    return queuedRequest != null;
}

答案 1 :(得分:0)

我担心这很糟糕,但是......也许值得为这个方法添加锁定?像

&#13;
&#13;
 private List<int> subscriptions = new List<int>();
&#13;
&#13;
&#13;

然后

&#13;
&#13;
 int subscriptinId = 1;//add calculation here
            int subscriptionIdIndex = subscriptions.IndexOf(subscriptinId);

            lock (subscriptions[subscriptionIdIndex])
            {
                //your method code
            }
&#13;
&#13;
&#13;

随意批评这种方法)