Monolithic and Microservices sample code examples in java

Category : Microservices | Sub Category : Microservices | By Prasad Bonam Last updated: 2023-07-11 08:54:14 Viewed : 332


Monolithic and Microservices sample code examples in java:

Here are simplified code examples in Java to illustrate the difference between a monolithic architecture and a microservices architecture:

Monolithic Architecture Example:

java
// Monolithic application with a single class public class MonolithicApp { public static void main(String[] args) { // Business logic UserService userService = new UserService(); String message = userService.getUserMessage(123); System.out.println(message); } } class UserService { public String getUserMessage(int userId) { // Database access and business logic String userName = UserRepository.getUserName(userId); return "Hello, " + userName + "!"; } } class UserRepository { public static String getUserName(int userId) { // Database query return "John Doe"; } }

In this example, the entire application is built as a single monolithic unit. The MonolithicApp class represents the entry point, and it directly calls the getUserMessage() method of the UserService class, which internally accesses the UserRepository to retrieve user information from the database.

Microservices Architecture Example:

java
// Microservices-based application with separate services // Service 1: User Service public class UserService { public String getUserMessage(int userId) { // Call Service 2: User Repository Service String userName = UserRepoService.getUserName(userId); return "Hello, " + userName + "!"; } } // Service 2: User Repository Service public class UserRepoService { public static String getUserName(int userId) { // Database query return "John Doe"; } } // Main Application public class MainApp { public static void main(String[] args) { // Business logic UserService userService = new UserService(); String message = userService.getUserMessage(123); System.out.println(message); } }

In this microservices example, we have two separate services: the UserService and the UserRepoService. The UserService calls the UserRepoService to retrieve user information. Each service can be developed, deployed, and scaled independently. They communicate with each other through well-defined APIs, enabling loose coupling between the services.

Keep in mind that these examples are simplified for illustration purposes, and in real-world scenarios, the implementation and communication between microservices would involve additional complexity and considerations, such as using RESTful APIs or message queues for inter-service communication.


Search
Related Articles

Leave a Comment: