Ekaterina
Ekaterina

Reputation: 1892

How to implement a scheduled job as a microservice

I have a Spring Boot application which provides REST API for Angular web interface.

There is also a scheduled job that is currently in this Spring Boot application. The job is to fill in the database with some enities, let's say books (they are taken from an external source, more specifically, from a web-site). I want to place this job into a separate microservice.

The question is whether the microservice should work directly with the shared database or access the main application via REST. In the first case some (if not the all) models and services will be shared, it doesn't look good. But in the second case each access to database will go through the first application. Is that ok?

Upvotes: 2

Views: 5900

Answers (2)

Chris
Chris

Reputation: 5643

Another option would be to use a queue like ActiveMQ instead of REST.

The cronjob-service fetches the books and validates the data for example. You can than store the data somewhere in file format like csv. It could be stored on a S3 Bucket on AWS or something like that. The cronjob-service than sends a refrence to that file via the queue and the database-service fetches the data and stores it.

The advantage over REST is, that a task can not be lost. If you're database-service is down or occupied for some reason, a REST request would return 404 and you have to implement a failsafe against it. With a queue, the task is stored within the queue. Even if a database-service instance starts handling the task and fails for some reason, the task is still in the queue and another database-service instance can pick it up and handle it.

Upvotes: 2

htshame
htshame

Reputation: 7330

Check out SOLID design principle.

S - is for Single Responsibility

There's also a pattern in microservice architecture with the very same name: Single Responsibility Principle

The single responsibility principle is one of the principles defined as part of the SOLID design pattern. It implies that a unit, either a class, a function, or a microservice, should have one and only one responsibility.

At no point in time, one microservice should have more than one responsibility.

You should decide which microservice should do what based on your application design, you definitely know it better than we do.

But having read your description I'd suggest the following:

  • your current database-microservice should be connected to DB and accept HTTP requests to save books in the database;

  • your new cronjob-microservice should start the job in time, get books from the website and send HTTP request to the database-microservice, hence it shouldn't be connected to the database.

Upvotes: 5

Related Questions