Julio Villane
Julio Villane

Reputation: 1034

Best way to limit parallel request in a @RestController method

Considering the following code:

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

What i want to accomplish is that if the method call from the TestService is being executed by 3 threads at the same time, the next execution generate a response with a HttpStatus.TOO_MANY_REQUESTS code.

Upvotes: 1

Views: 452

Answers (1)

Julio Villane
Julio Villane

Reputation: 1034

Thanks to @pvpkiran comment I managed to code this:

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

With the corresponding exception definition:

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

Upvotes: 2

Related Questions