考虑以下代码:
@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
代码的响应
答案 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{ }