How to save the client requests, which got failed, to database in spring boot?
Background I am working on a service which accepts the request from client(s), process it and make call(s) to different downstream services using RestTemplate to fetch some data, and then use those responses to frame my service response to return to the client. Client's requests can be sync(REST API) or async(consumed from queue/messaging system, say, Kafka). My service is a spring boot app. Database used is Azure cosmosdb.
Problem Statement and Question I need to save every incoming request (whether it is sync or async) to Database (collection name- payloads) with its completion status (success or failed). Along with this, I also need to save the request to "retry" collection if it gets failed when calling downstream services. For example - I received a request from client, and I make a call to a downstream service, and it resulted in timeout. So I want this request to be saved in "payloads" collection with status as failed, and also want to store in "retry" collection so that I can retry it at later point of time once that downstream is up and running.
The question is - Since the request failure can happen at any point during the whole execution, How can I write the code to save these into DB at a single place, so that irrespective of where the failure occurred, save to DB is executed, and I do not have to call save to DB manually at each possible failure point. Please see below sample code.
public class MyController { // to process clients request synchronously
@PostMapping("/v1")
public ResponseEntity\<ResponseDTO\> do(@RequestBody RequestDTO requestDTO) {
myService.do(requestDTO);
return new ResponseEntity\<\>(response, HttpStatus.OK);
}
}
public class MyKafkaConsumer { // process clients request asynchronously
public void consume(RequestDTO requestDTO) {
myService.do(requestDTO);
}
}
public class MyService { // actual business logic class
public void do(RequestDTO requestDTO) {
Data data1 = downstream1Client.getData();
helperClass.doSomething();
}
}
public class HelperClass {
public void doSomething() {
Data data = downstream2Client.getData();
}
}
public class Downstream1Client {
public Data getData() {
// rest template call
if 5xx response, save failed req to DB
}
}
public class Downstream2Client {
public Data getData() {
// rest template call
if 5xx response, save failed req to DB
}
}
Checked multiple posts at stackoverflow, explored Google, I got the answer for how to save the request, but could not find the answer for my failure scenario.
Comments
Post a Comment