gpt4 book ai didi

java - 如何检测方法发布中同一时间的重复请求

转载 作者:行者123 更新时间:2023-12-01 17:45:10 25 4
gpt4 key购买 nike

我使用 spring boot 并使用如下所示的方法创建 api:

@RestController
@RequestMapping("/api/products/")
@Api(value = "ProductControllerApi",produces = MediaType.APPLICATION_JSON_VALUE)
public class ProductController {
@PostMapping
public ResponseEntity<ProductDto> createProduct(@RequestBody Product product) {
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(product.getId()).toUri();
return ResponseEntity.created(location).body(productService.createProduct(product));
}
}

但是当用户使用设备同时调用我的方法(/api/products/)时,它会使用相同的数据重复创建。示例:当使用创建用户时看起来像{ “名称”:“三星” “成本”:“26 美元”}

它在数据库中创建两条具有相同数据的记录。如何检测来自不同来源的重复数据(示例:用户使用两个手机并使用相同的方法同时调用并创建相同的数据)。如何避免它,如果它同时调用相同的数据,它只会将一条记录插入数据库

最佳答案

这不是 Spring Boot 的问题,而是持久层的问题。最佳实践是以这样的方式对数据库表进行建模:两个相同的请求将创建完全相同的主键。然后,您的应用程序代码将在事务提交时处理来自数据库层的任何异常。

关于java - 如何检测方法发布中同一时间的重复请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com