Reputation: 498
I would like to ask what is the best approach to run a long process using Spring. I have a webapp and when the client does a request it runs a Spring controller. This Controller would get some parameters from the request and then runs a query and fetch records from the DB.
The records from the DB are high, i need to do a comparing logic which may take a long time, so I need to run it separately. When this process is executed , it should write the final results into an excel file and mail it.
Upvotes: 9
Views: 7105
Reputation: 3724
You can use the annotation @Async
to return immediately.
Fisrt, write a @Service
class to process you DB and Excel job.
@Service
public class AccountService {
@Async
public void executeTask(){
// DB and Excel job
}
}
Then, In controller method trigger the task
@Controller
public class taskController{
@RequestMapping(value = "as")
@ResponseBody
public ResultInfo async() throws Exception{
accountService.executeTask();
return new ResultInfo(0, "success", null);
}
}
At last, add this to application-context.xml(spring config file)
<task:annotation-driven executor="taskExecutor"/>
<task:executor id="taskExecutor" pool-size="10"/>
Hope this will help you.
Upvotes: 6