This is very much possible in Spring by making use of @Async
task processing.
First create a service which will perform the task asynchronously. Here make note of the @Async
annotation, on performTask
method, which will be scanned and marked by spring for asynchronous execution.
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
@Service
public class AsyncTask {
@Async
public Future<Result> performTask(String someArgument) {
// put the business logic here and collect the result below
Result result = new Result(); // this is some custom bean holding your result
return new AsyncResult<Result>(result);
}
}
Next create a component (optional - can be from any other existing service as well) which will invoke the above service.
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AsyncClass {
@Autowired
private AsyncTask asyncTask;
public void doAsyncOperation() throws Exception {
List<Future<Result>> futures = new ArrayList<Future<Result>>();
for (int i = 1; i < 10; i++) {
// Simulate multiple calls
Future<Result > future = doAsync(String.valueOf(i));
futures.add(future);
}
for (Future<Result > future : futures) {
// fetch the result
Result result = future.get();
// process the result
}
}
private Future<Result> doAsync(final String someArgument) {
// this will immediately return with a placeholder Future object which
// can be used later to fetch the result
Future<Result> future = asyncTask.performAsync(someArgument);
return future;
}
}
The sample xml configuration required to enable async is as below (For annotation based config use @EnableAsync)
<task:annotation-driven executor="myExecutor" />
<task:executor id="myExecutor" pool-size="30" rejection-policy="CALLER_RUNS"/>
For detailed documentation refer here
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…