如何防止 Web 服务 API 中的并发? [英] How to prevent concurrency in web service API?

查看:36
本文介绍了如何防止 Web 服务 API 中的并发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有三个网络服务(/a/b/c),其中每个服务都映射到一个方法(go()) 在一个单独的 Java 类(ClassAClassBClassC)中.

We have three web services (/a, /b, /c) where each service maps to a method (go()) in a separate Java class (ClassA, ClassB, ClassC).

只能同时运行一个服务(即:/b 不能在 /a 运行时运行).然而,由于这是一个 REST API,没有什么可以阻止客户端请求并发运行的服务.

Only one service should run at the same time (ie: /b cannot run while /a is running). However as this is a REST API there is nothing to prevent clients from requesting the services run concurrently.

在服务器上强制服务并发运行的最佳和最简单的方法是什么?

What is the best and most simple method on the server to enforce that the services don't run concurrently?

更新:这是一个内部应用,我们不会有很大的负载,只有一个应用服务器.

Update: This is an internal app, we will not have a large load and will just have a single app server.

更新:这是一个主观问题,因为您可以对影响最终答案的一般应用程序设计提出不同的论点.接受 overthink 的答案,因为我发现它最有趣和最有帮助.

Update: This is a subjective question as you can make different arguments on the general application design which affects the final answer. Accepted overthink's answer as I found that most interesting and helpful.

推荐答案

假设仅仅强制 Web 服务器只有一个监听线程服务请求是不行的...我想我只是使用静态锁(ReentrantLock 可能,为了清楚起见,虽然你可以在任何共享对象上同步,真的):

Assuming it's not ok to just force the web server to have only one listening thread serving requests... I suppose I'd just use a static lock (ReentrantLock probably, for clarity, though you could sync on any shared object, really):

public class Global {
  public static final Lock webLock = new ReentrantLock();
}

public class ClassA {
    public void go() {
        Global.webLock.lock()
        try {
            // do A stuff
        } finally {
            Global.webLock.unlock()
        }
    }
}

public class ClassB {
    public void go() {
        Global.webLock.lock()
        try {
            // do B stuff
        } finally {
            Global.webLock.unlock()
        }
    }
}

public class ClassC {
    public void go() {
        Global.webLock.lock()
        try {
            // do C stuff
        } finally {
            Global.webLock.unlock()
        }
    }
}

这篇关于如何防止 Web 服务 API 中的并发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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