问题
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.
Here is the controller and service layer:
@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
}
}
Questions:
Assuming someone pulls the network cable right after the service call, so the transaction is comitted.
1) Will Spring throw an exception if the response cannot be delivered?
2) Is it possible to rollback the transaction if the response cannot be delivered?
3) How can I make sure the database stays consistent when the client retries? (the POST is not idempotent).
Thanks!
回答1:
I'll try to answer you questions:
1) Maybe. It depends on size of answer and exact moment when connection is lost.
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.
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.
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) With Spring answer will be NO.
3) It is up to you. There is no universal answer. For example Hibernate
can be configured to use versioning on your objects.
来源:https://stackoverflow.com/questions/44908138/how-to-rollback-a-transaction-if-the-post-response-could-not-be-delivered