Web API方法排队 [英] Queuing for web api methods

查看:129
本文介绍了Web API方法排队的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web api方法:-

I have one web api method :-

[POST]
public void SaveData()
{
}

我想以一种方式实现,如果SaveData()方法中的代码已经被执行,那么SaveData方法将不接受任何其他调用.

I want to implement in such a way that , if code inside SaveData() method is already getting executed , then SaveData method will not accept any other call.

即我想将对savedata方法的调用保持在队列中.当一个电话结束时,将发生另一个电话.

i.e. I want to keep calls to the savedata method in a queue. When one call will finish , other call will occure.

注意:-调用SaveData()方法不在我的范围内.我无法决定以同步方式还是异步方式调用此api方法.

Note:- Calling SaveData() method is not within my scope. I can not decide to call this api method synchronously or asynchronously.

在我的范围内,唯一的事情就是为SaveData方法编写代码.它将被称为彻底的外部系统.

Only thing within my scope is writing code for SaveData Method. It will be called thorough external system.

推荐答案

我强烈建议您在应用程序中使用消息队列系统. mjwills 在评论部分提供了两种出色的消息代理软件解决方案:

I strongly suggest that you use a message queuing system in your application. mjwills provided two great message-broker software solutions in the comments section:

  • RabbitMQ: is open-source lightweight and easy to deploy on premises and in the cloud
  • Amazon Simple Queue Service (SQS): is a fully managed cloud based solution provided by AWS

在您可以在应用程序中使用任何这些解决方案之前,都需要进行集成,但是之后将非常简单:

There's an integration effort before you can use any of these solutions in your app, but afterwards it will be as simple as:

[POST]
public void SaveData()
{
    var msg = new SaveDataMessage();
    /* populate msg object... */

    this.queueClient.Publish(msg);
}

此伪代码将消息发布到队列.另一方面,队列订户将按顺序接收和处理这些消息,例如:

This pseudo-code publishes a message to the queue. On the other end a queue subscriber will be receiving and processing theses messages sequentially, for instance:

public void OnMessage(SaveDataMessage msg)
{
    /* process message... */
}

其他好处是 i),订阅者可以在独立的进程中运行,这意味着您的API请求可以立即返回,并且后台工作人员会处理消息 ii)随着您的应用程序的扩展,该架构将与负载平衡的API兼容.

Additional benefits are i) the subscriber can run in an independent process, which means your API request can return immediately, and a background worker will take care of processing messages ii) this architecture will be compatible with load balanced APIs, as your app scales up.

尽早在应用程序中构建此结构绝对是值得的.从长远来看,它将为您提供更大的灵活性和生产力.

It's definitely worth the effort of building this structure early on into your app. It will give you more flexibility and productivity in the long run.

我写了一篇有关此主题的文章,其中包含此答案的更多详细补充信息:

I have written an article about this subject which contains more detailed, complementary information to this answer: Using queues to offload Web API

这篇关于Web API方法排队的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆