如何在ServletAPI(Spring MVC)中限制每个USER的请求

Nod*_*bek 5 java spring spring-mvc servlet-filters

如何允许@PathVariable每个用户使用特定URL的micorservice方法只有一个请求.我的控制器

@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);
    }
Run Code Online (Sandbox Code Playgroud)

例如 :

  1. /rest/product/ID/2231USER允许的第一个请求(登录名="xaxa")
  2. /rest/product/ID/2545USER允许的第二个请求(登录名="xaxa")
  3. /rest/product/ID/2231USER不允许第三个请求(使用login ="xaxa")

哪个是实现此功能的最佳方式?(我是否要通过DB中的用户登录来保留此URL请求,或者已经存在解决方案)

Raf*_* G. 2

您可以使用 AOP 并实现您自己的方面,该方面将被称为 Before your Rest Endpoint 方法。

该切入点将读取请求中提供的 ID,并尝试查找与该 ID 对应的锁。然后就是通常的情况 - 尝试访问资源并可能等待。

实现可以基于 Guava 的Striped类——至少在一开始是这样。

有几个问题需要考虑:

  1. Striped 可以替换为一些 LRU Cache,以实现更好的内存管理。
  2. 当然,当两个请求同时访问同一个 ID 时,您必须提供同步。
  3. 它仅适用于部署在单个节点上的应用程序。
  4. 从性能角度来看,这不是一个很好的方法。根据您的流量,这可能是一个问题。