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.
Advantages of Spring Boot:It reduces lots of development time and increases productivity. It avoids writing lots of boilerplate Code, Annotations and XML Configuration. It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
I suggest doing the following: Annotate response methods with @Cacheable("#yourKey") . Also, remember to add @EnableCaching to the application. Call the cached response method from within the application after it starts to reduce the time consumed for next calls.
The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With