如果无法传递POST响应,如何回滚事务 [英] How to rollback a transaction if the POST response could not be delivered

查看:174
本文介绍了如果无法传递POST响应,如何回滚事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring MVC,假设我已经实现了一个控制器,该控制器处理POST请求,在事务内部执行数据库操作并在响应正文中返回结果.

Using Spring MVC, assume I have implemented a controller that handles a POST request, performs a database operation inside a transaction, and returns a result in the response body.

这是控制器和服务层:

@RestController
@RequiredArgsConstructor
public class SomeController {

  private final SomeService someService;

  @PostMapping("/something")
  public SomeResult postSomething(Something something) {
    return someService.handle(something);
  }

}

@Service
@RequiredArgsConstructor
public class SomeService {

  private final SomeRepository someRepository;

  @Transactional
  public SomeResult handle(Something something){
    // changes to the database
  }

}

问题:

假设有人在服务呼叫后立即拔出网线,那么就开始了事务.

Assuming someone pulls the network cable right after the service call, so the transaction is comitted.

1)如果无法传递响应,Spring会抛出异常吗?

1) Will Spring throw an exception if the response cannot be delivered?

2)如果无法传递响应,是否可以回滚事务?

2) Is it possible to rollback the transaction if the response cannot be delivered?

3)如何确保客户端重试时数据库保持一致? (POST不是幂等的.)

3) How can I make sure the database stays consistent when the client retries? (the POST is not idempotent).

谢谢!

推荐答案

我将尝试为您解答问题:

I'll try to answer you questions:

1)也许.这取决于答案的大小和失去连接的确切时间.

1) Maybe. It depends on size of answer and exact moment when connection is lost.

如果当spring尝试向套接字OS写入响应时检测到TCP/IP连接已关闭,将引发异常. TCP协议不包含检测这种情况的内部过程,因此OS使用诸如超时之类的试探法.

Exception will be thrown if when spring try to write response to socket OS detect that TCP/IP connection is closed. TCP protocol do not contain internal procedure of detection such situation so OS use heuristics like timeouts.

所以我在这里只看到一个选项. Spring尝试将响应写入套接字,但响应太大而无法容纳在缓冲区中.在这种情况下,写操作将被阻止.然后一段时间后,它将由于超时而中断,并引发异常.

So I see only one option here. Spring try to write response to socket, but response too big to fit in buffer. In this situation write operation will be blocked. Then after some time it will be interrupted because of timeout and exception is raised.

我不确定100%我的答案正确无误,因此您最好自己检查一下. 我建议您不要依赖这种机制,因为它取决于许多不同的因素,例如缓冲区大小,超时和Spring实现.

I'm not 100% sure that my answer accurate, so you better check it yourself. I suggest you not rely on this mechanics because it depend on many different factors like buffer size, timeout and Spring implementation.

2)对于Spring,答案将为.

2) With Spring answer will be NO.

3)由您决定.没有普遍的答案.例如,可以将Hibernate配置为在对象上使用版本控制.

3) It is up to you. There is no universal answer. For example Hibernate can be configured to use versioning on your objects.

这篇关于如果无法传递POST响应,如何回滚事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆