0

I am working on a Spring Webflux project,

I want to do something like, When client make API call, I want to send success message to client and perform large file operation in background.

So client does not have to wait till my entire file is process.

For try out I made sample code as below

REST controller

@GetMapping(value = "/{jobId}/process")
  @ApiOperation("Start import job")
  public Mono<Integer> process(@PathVariable("jobId") long jobId) {
    return service.process(jobId);
  }

File processing Service

public Mono<Integer> process(Integer jobId) {
    return repository
        .findById(jobId)
        .map(
            job -> {
              File file = new File("read.csv");
              return processFile(file);
            });
  }

Following is my stack

Spring Webflux 2.2.2.RELEASE

I try to make this call using WebClient, but till entire file is not processed I am not getting response.

Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
Alpesh Jikadra
  • 1,692
  • 3
  • 18
  • 38

2 Answers2

1

As one of the options, you can run processing in a different thread.

For example:

  1. Create an Event Listener Link

  2. Enable @Async and @EnableAsync Link

Or use deferent types of Executors from Java concurrency package

Or manually run the thread

Also for Kotlin you can use Coroutines

Ihar Sadounikau
  • 741
  • 6
  • 20
1

You can use the subscribe method and start a job with its own scope in background.

Mono.delay(Duration.ofSeconds(10)).subscribeOn(Schedulers.newElastic("myBackgroundTask")).subscribe(System.out::println);

As long as you do not tie this to your response publisher using one of the zip/merge or similar operators your job will be run on background on its own scheduler pool.

subscribe() method returns a Disposable instance which can later be used cancel the background job by calling dispose() method.

Akhil Bojedla
  • 1,968
  • 12
  • 19
  • But how does this gets execute ? as Subscribe method is returning the Disposable, who is going to use it as I want to run this in background ? – Alpesh Jikadra Jan 28 '20 at 06:26
  • You can put this in your `job` lambda. You would only need `Disposable` if you need to cancel this background job for some reason. You can ignore it if you don't have that requirement. – Akhil Bojedla Jan 30 '20 at 15:58