Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit requests per USER in ServletAPI (Spring MVC)

How can I allow only a one request to micorservice method with specific URL @PathVariable per User. My Controller

@RestController
@RequestMapping(value = "/rest/product", produces = "application/json;charset=UTF-8")
public class ProductRestController {
    @Autowired
    ProductService productService;

    @Autowired
    ProductAsm productAsm;

    @RequestMapping(value = "/ID/{ID}", method = RequestMethod.GET)
    public ResponseEntity<ProductResource> getProductID(@PathVariable("ID") Long ID, @AuthenticationPrincipal User) {

        Product product = productService.getProduct(ID);
        if (product == null)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);

        return new ResponseEntity<>(productAsm.toResource(product), HttpStatus.OK);
    }

For example :

  1. first request /rest/product/ID/2231 allowed for USER(with login="xaxa" )
  2. second request /rest/product/ID/2545 allowed for USER(with login="xaxa" )
  3. thirdth request /rest/product/ID/2231 not allowed for USER(with login="xaxa" )

Which is the best way to implement this functionality?(Have I to keep this URL request with User login in DB or there is already solutions)

like image 427
Nodirbek Shamsiev Avatar asked Sep 02 '15 06:09

Nodirbek Shamsiev


1 Answers

You could use AOP and implement your own aspect that would be called Before your Rest Endpoint method.

This pointcut would read ID provided in a request and would try to find a Lock corresponding with this ID. Then the usual - try to access resource and potentially wait.

Implementation could base on Guava's Striped class - at least for the start.

There are several problems that need to be taken into consideration:

  1. Striped could be replaced with some LRU Cache for better memory management.
  2. You would of course have to provide synchronization for the case when the same ID is accessed simultaneously by two requests.
  3. It would work only for an application deployed on a single node.
  4. It would not be very good approach performance-wise. Depending on your traffic this may be an issue.
like image 57
Rafal G. Avatar answered Oct 04 '22 17:10

Rafal G.