【问题标题】:Best way to limit parallel request in a @RestController method在 @RestController 方法中限制并行请求的最佳方法
【发布时间】:2019-02-05 12:16:57
【问题描述】:

考虑以下代码:

@RestController
@RequestMapping("/requestLimit")
public class TestController {

    @Autowired
    private TestService service;

    @GetMapping("/max3")
    public String max3requests() {
        return service.call();
    }
}

@Service
public class TestService {

    public String call() {
        //some business logic here
        return response;
    }
}

我想要完成的是,如果 TestService 中的方法 call 同时被 3 个线程执行,则下一次执行会生成带有 HttpStatus.TOO_MANY_REQUESTS 代码的响应。

【问题讨论】:

  • 您必须在控制器类中保留一个原子变量并递增。在你的方法中增加它并检查它是否超过 3,如果是,则返回,否则继续
  • 谢谢@pvpkiran,有了你的推荐,我设法提出了一个答案
  • 使用专为此设计的Semaphore

标签: spring-boot threadpool spring-restcontroller


【解决方案1】:

感谢@pvpkiran 的评论,我设法编写了这个代码:

@RestController
@RequestMapping("/requestLimit")
public class TestController {

    private final AtomicInteger counter = new AtomicInteger(0);

    @Autowired
    private TestService service;

    @GetMapping("/max3")
    public String max3requests() {
        while(true) {
            int existingValue = counter.get();
            if(existingValue >= 3){
                throw new TestExceedRequestLimitException();
            }
            int newValue = existingValue + 1;
            if(counter.compareAndSet(existingValue, newValue)) {
                return service.call();
            }
        }
    }
}

@Service
public class TestService {

    public String call() {
        //some business logic here
        return response;
    }
}

有对应的异常定义:

@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public class TestExceedRequestLimitException extends RuntimeException{ }

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 2010-09-07
    • 2021-07-06
    • 2018-10-25
    • 2011-10-21
    • 2010-11-29
    • 2019-08-06
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多