我如何只允许每个用户对具有特定 URL @PathVariable
的微服务方法发出一个请求。
我的 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);
}
例如:
- USER 允许第一个请求
/rest/product/ID/2231
(with login="xaxa") - 第二个请求
/rest/product/ID/2545
允许 USER(with login="xaxa") - USER 不允许第三次请求
/rest/product/ID/2231
(with login="xaxa")
实现此功能的最佳方式是什么?(我是否要将此 URL 请求与用户登录一起保留在数据库中,或者已经有解决方案)
最佳答案
您可以使用 AOP 并实现您自己的方面,该方面将在您的 Rest Endpoint 方法之前调用。
此切入点将读取请求中提供的 ID,并尝试找到与此 ID 对应的锁。然后通常 - 尝试访问资源并可能等待。
实现可以基于 Guava 的 Striped类 - 至少在开始时是这样。
有几个问题需要考虑:
- Striped 可以用一些 LRU 缓存代替,以实现更好的内存管理。
- 您当然必须为两个请求同时访问同一 ID 的情况提供同步。
- 它仅适用于部署在单个节点上的应用程序。
- 在性能方面这不是很好的方法。根据您的流量,这可能是个问题。
关于java - 如何在 ServletAPI (Spring MVC) 中限制每个用户的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32346150/