简体   繁体   English

如何处理并发api调用

[英]How to handle concurrent api calls

I have this Rest API to getGroupId which will increment the counter, and return the group id when we call this getGroupId.我有这个 Rest API 到 getGroupId,它会增加计数器,并在我们调用这个 getGroupId 时返回组 ID。 But it is returning the duplicate sequence number when I'm making concurrent calls.但是当我进行并发调用时它返回重复的序列号。 Can anyone help me how to handle this concurrent API requests.任何人都可以帮助我如何处理这个并发 API 请求。

@RequestMapping(value = "/groupid/get/{dbindex}/{dc}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Object getGroupId(@PathVariable Integer dbindex, @PathVariable Object dc) {

        service.setDB(dbindex);
        if (service.get("groupid", dc) == null) {
            BigInteger groupid = new BigInteger("1");
            service.set("groupid", dc, groupid);
            return service.get("groupid", dc);
        } else {
            BigInteger groupid = new BigInteger(String.valueOf(service.get("groupid", dc)));

            BigInteger updated = groupid.add(new BigInteger("1"));

            service.set("groupid", dc, updated);
            return service.get("groupid", dc);
        }
    }

The simplest way to solve this is to add the synchronized keyword to the getGroupId method declaration.解决此问题的最简单方法是在 getGroupId 方法声明中添加synchronized关键字。 It will prevent multiple threads from executing the method at the same time.它将防止多个线程同时执行该方法。

It may not be the best way to solve it, however.然而,这可能不是解决它的最佳方法。 If a synchronized method is called by multiple threads concurrently, they will have to take their turns, one at a time.如果一个同步方法被多个线程同时调用,它们将不得不轮流调用,一次一个。 If it's expected that the method will be called with high concurrency it could be a performance issue.如果预计该方法将以高并发性调用,则可能是性能问题。

Better solutions may be available but they would require changes that go beyond the scope of the code you have shown.可能有更好的解决方案,但它们需要超出您显示的代码范围的更改。 If the only code you can change is in this method, you have to synchronize it to make your code thread safe.如果您可以更改的唯一代码在此方法中,则必须对其进行同步以使您的代码线程安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM