A common design in event driven architecture in microservices.
From my current experience as software developer, I have seen multiple projects using this simple architecture pattern in microservices, which is very simple to understand and implement yet very effective with very less rate of error.
What is event driven architecture?
Simply put, event driven architecture deals with actions based on certain events. Common example is publishing of messages by a producer, consuming of that messages by the consumer.
Let us understand with a small example:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private ApplicationEventPublisher eventPublisher;
@PostMapping("/register-event")
public String registerUser(@RequestBody UserRegistrationRequest request) {
// Logic to register user…
// Publish the user registration event
eventPublisher.publishEvent(new UserRegisteredEvent(this, request.getUsername()));
return "User registered successfully";
}
}
@RestController
public class EventController {
…..
@PostMapping("/consume-event")
public String consumerEvent(String eventId) {
…..
//Logic to consume specific event
}
@PostMapping("/consume-pending-event")
public String consumerPendingEvents() {
…..
//Logic to consume pending events
}
}
Let us assume the UserController is in the main application, which contains APIs for registering the users.
To use this API when needed, we can use another app for polling for consuming the event and consuming the pending events as well.
Based on the use case, we can add other APIs to consume/edit/delete the events as well.
This common pattern is observed in event-driven applications.