Home > Software design >  Spring Boot - How to trigger a task after request to an endpoint has been completed
Spring Boot - How to trigger a task after request to an endpoint has been completed

Time:05-26

I have somewhat unusual requirement for one of my POST requests. It has to do following:

  1. controller receives request and calls a service (which then calls JpaRepository) to persist data in a database
  2. return response (2xx, 4xx, 5xx) based on result from #1 above
  3. then immediately call another service to send the same data it persisted to another API

#1 and #2 above are clear and working just fine

But #3 is unusual because at that point, the request is already completed and response was already sent to the client in #2 step. (Basically, the client considers its request success if it has been persisted to the database, regardless if it was forwarded to the other API for further processing).

This means that #3 needs to be somehow triggered after the fact or some other way.

I believe, but not sure, C# would use something like Tasks for this and have task completion block to take over #3 (or maybe something else).

But I have no idea what would be appropriate for such a scenario in Spring Boot?

CodePudding user response:

I think your best bet would be to use Events in Spring Boot. This and this are good articles you can checkout.

Events in Spring are synchronous by default, but you may consider asynchronous events if you do not necessarily have to wait before sending back a response for your requests.

CodePudding user response:

As @Salmane Tamo suggested, you can just do a asynchronous call to other API before returning the response. It can just be as simple as having @Async on a public void method & @EnableAsync. Ref: Spring Async. As calling service don't care about this API call, you can error log in cases of any error responses from your API call.

  • Related