[英]How to handle when call requests at same time
I am using Spring boot create a restful for save data to Database. 我正在使用Spring boot创建一个restful,用于将数据保存到数据库。 Now I have problem when you call this service in the same time my data its duplicated in database because previous request not finish yet.
现在,当您同时调用此服务时,我遇到了问题,因为先前的请求尚未完成,因此我的数据在数据库中重复了。
I generate number like 00001 I need to running its from database 我生成像00001这样的数字,我需要从数据库中运行它
but when request same time in database save 00002 for 2 records. 但是当请求在数据库中同时进行时,将00002保存为2条记录。
@Transactional
public List<Object> saveData(String data) {
//validate data
//Get Last Data
//set prepare data
//save data
int idLatest = Integer.parseInt(getLatest("7", "8"));
List<Object> objects = autoGenarateEntity(idLatest);
Repository.save(Object);
}
public String getLatest(String idFirst, String idSecond){
Optional<Object> running = Repository.findByBIdStartingWithOrderByBIdDesc(idFirst, idSecond).stream().findFirst();
if(running.isPresent()){
String bId =running.get();
return bId.getBId();
}else {
return "70000000";
}
}
public List<Object> autoGenarateEntity(int idLatest){
List<Object> objects = new ArrayList<>();
IntStream.range(1, 5 + 1).forEach(i -> {
Object obj = new Object();
obj.setBId(Integer.toString(idLatest + i));
obj.add(Object);
});
return objects;
}
Following are the options that can be done in this case: 以下是在这种情况下可以执行的选项:
1.) have unique key constraint for the column having the value of 00001. So that, the second transaction which was trying to commit same value would roll-back. 1.)对值为00001的列具有唯一的键约束。因此,试图提交相同值的第二个事务将回滚。 And you could use Spring-Retry mechanism to execute the second transaction with updated value
您可以使用Spring-Retry机制执行具有更新值的第二个事务
2.) Use a custom sequence Generator to increment the value, instead of handling it yourself. 2)使用自定义序列生成器增加值,而不是自己处理。
I have a solution for this 我对此有解决方案
@Transactional(isolation = Isolation.SERIALIZABLE)
and use spring retry 并使用spring retry
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.