简体   繁体   中英

How to send multiple response for a request using java

I am attempting to send multiple responses at certain interval of time for a http-request from client.I am using Spring Boot RESTful web serives which receives a request from AngularJs client. RESTFul web services will get list of jobs from client, i need to send response to the client after the completion of each Job.

@PostMapping("/runExecution")
public Object sendingMultipleResponse(String input){

  for(Object obj : ListOfJobs){
    //performs business logic
    return object;
  }

}

Consider 10 Jobs are there in the lists, i need to return the results to the request after the execution of each job. NOTE: For a single request from AngularJs, i need to send multiple responses

You can use WebSocket for your scenario. WebSocket provides full duplex communication channel between a server and client. When client sends message (let say request in this case) on server, server will start processing the message and server will respond to the client with the response message (it will be response ) like sending status of the message being processed or status of the job that has been triggered by the message sent over the WebSocket . Please refer link

You can try the following design:
1) client sends a multiple jobs request to the server
2) the server starts working on the jobs and saves the response in some DB
3) client pulls the responses at some interval from the server and gets the response for the jobs that are completed

it is not a perfect solution, since the client is doing many pulls and needs to know when to stop (after all jobs finished) but it is easy to implement and reduces the network dependancy (since no need to leave an open connection to the server).

i am following below two tutorials maybe they will help you too. The spring module in question is Spring Reactor https://projectreactor.io/

https://dzone.com/articles/spring-boot-server-sent-events-tutorial

https://dzone.com/articles/reactor-core-tutorial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM