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

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

问题描述

我们有三个网络服务( / a / b / c )其中每个服务映射到一个单独的Java类中的方法( go())( ClassA ClassB ClassC )。



一个服务应该同时运行(即: / b 无法运行,而 / a 正在运行)。但是,由于这是一个REST API,因此没有什么可以阻止客户端请求服务并发运行。



服务器上最好和最简单的方法是强制执行服务不同时运行






更新:这是一个内部应用程式,

更新:这是一个主观问题,因为您可以对一般应用程序设计进行不同的争论,影响最后的答案。接受overthink的答案,因为我发现最有趣和有用的。

解决方案

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

  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()
}
}
}


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

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.

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.

解决方案

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天全站免登陆