限制@RestController方法中的并行请求的最佳方法

时间:2018-08-30 14:00:01

标签: spring-boot threadpool spring-restcontroller

考虑以下代码:

@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;
    }
}

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

1 个答案:

答案 0 :(得分: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{ }