What is the recommended way to start processes in the background using Spring?

I am working on a web application with Spring (Boot, MVC), and there will be some things that need to be run in the background, so I am not blocking the request.

Currently, I was thinking that the Spring batch job runs every 5 minutes and checks in the table (jobs_queue) in the database if there is anything to do, and then perform the tasks (assuming that each row in the table is required).

Obviously, this is not a good scalable solution (I think), since I will have only one worker (if there are too many tasks in the queue, this only worker may not cope with the load), and he will also have at least one DB query every 5 minutes (you can also see if there are jobs in the queue).

Which is better for this?

+7
java spring spring-boot spring-batch spring-mvc
source share
3 answers

Adding to @kotabek's answer, Spring The package has the ability to run tasks through messages. That way, you can have JobLaunchingMessagHandler listen to requests to run the job and run it accordingly. This allows you to process this use case both locally (with direct channels) and remotely (via some middleware messaging software such as Rabbit). You can read more about this in the documentation: http://docs.spring.io/spring-batch/reference/htmlsingle/#launching-batch-jobs-through-messages

+4
source share

If you're using Spring 4, check out the @Scheduled annotation.

Example:

 @Component public class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System.out.println("The time is now " + dateFormat.format(new Date())); } } 

Link to the code - https://spring.io/guides/gs/scheduling-tasks/

A quick note: remember to add @EnableScheduling to your configuration.

+3
source share

I recommend using RabbitMQ or ActiveMQ. Thus, you can write tasks in the request, and when someone or something adds a task, your work will work. I think you can integrate it with db and listen to insert events.

+2
source share

All Articles