Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Best approach to run a long process using Spring

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.

like image 903
Manish Sahni Avatar asked Aug 17 '13 16:08

Manish Sahni


People also ask

Does spring boot reduce development time?

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.

How do I reduce the response time on a REST API spring boot?

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.

What are the methods in spring boot?

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.


1 Answers

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.

like image 153
Larry.Z Avatar answered Oct 13 '22 10:10

Larry.Z