Ad

Node Response.end() Equivalent In Spring

- 1 answer

Is there any way in spring that we can send response immediately.

I want to create a thread which will do a job. But I don't want to make the user to wait till that job completed.

Ad

Answer

There is multiple way of doing so in Spring.

Here is their article.

If you want to make the operations asynchronously, the easiest way is to use the @Asyn annotation from Spring.

Here is a simple example :

// Interface definition for your async operation here
public interface AsyncOperator {

    @Async
    void launchAsync(String aBody);
}

And a simple implementation that uses the interface

// Need to be a bean managed by Spring to be async
@Component
class SimpleAsync implements AsyncOperator {
    @Override
    public void launchAsync(String aBody){
        // Your async operations here
    }
}

Then you need for Spring to configure how the async works. Using Spring boot a simple configuration class like this works:

@Configuration
@EnableAsync
public class AsyncConfiguration {
}

Then you can call your method and it will return right away and do the treatments asynchronously :

@Component
public class AController {
    private final AsyncOperator async;
    public AController(AsyncOperator async){
        this.async = async;
    }

    public String aMethod(String body){
        // here it will return right after call
        this.async.launchAsync(body);

        return "Returned right away !!";
    }
}

The only downsides of this method is that all your classes for async operations must be managed by Spring.

Ad
source: stackoverflow.com
Ad