In this tutorial we are going to learn how to develop microservices using spring boot with examples. Main focus of this tutorial is on learning by doing hands-on. Before hands-on we will first understand what is microservices and related terminologies like DDD, 12-Factors App, Dev Ops.
Opposite to microservice, with monolithic application it focuses on all the functionality or modules in a single application. So when any changes required to monolithic application it has to deploy and test the complete application while with microservice it has to develop and deploy only affected component which is a small service. It saves lot of development and deployment time in a large application.
It's basically an architectural style which can be followed to develop an application as a small service which is independent or may be interdependent (talking to other service to complete the job).
Below are the twelve factors which I have copied from Wikipedia for your ease.
This twelve factors attribute specifies almost most of the thing to be taken care for microservices development but still there are several patterns which can be applied as per business requirement. For example Database per Service pattern also can be used which says each microservice should have it's own database and it must not be shared by other services.
Now in further sections we will see the development of all components mentioned in above architecture.
Now you can enter below URL to test the service directly.
http://localhost:8080/users
To test the service through API gateway and discovery server, you need to open below URL in browser.
http://localhost:9999/users/
Both of the above URLs will give you same results.
What is a Microservice
In simple terms microservice is a piece of software which has a single responsibility and can be developed, tested & deployed independently. In microservices we focus on developing independent and single fully functioning modules.Opposite to microservice, with monolithic application it focuses on all the functionality or modules in a single application. So when any changes required to monolithic application it has to deploy and test the complete application while with microservice it has to develop and deploy only affected component which is a small service. It saves lot of development and deployment time in a large application.
It's basically an architectural style which can be followed to develop an application as a small service which is independent or may be interdependent (talking to other service to complete the job).
Designing Microservice
While designing application developers and domain experts should speak the same language so both have the same understanding. When we design a microservice we need to follow specific approach/ patterns, for example: DDD. When developing microservice then we need to make sure that our microservice implements certain attributes, for example: 12-factors. And then we can have other common design pattern/principles for application development.1. What is Domain driven design (DDD)
DDD is a top to bottom design approach similar to OOAD which helps to reflect the business domain into software. It helps defining the domains, elements, their relationship, boundary and communication to replicate the real business. That's why we say it focuses on the business domain and good domain knowledge is required to design the system perfectly. Having complete domain knowledge is good for any application but in my experience I have seen when developers know only the portion of application where they are working actually. But when we design system in small pieces it becomes very important to understand the whole system and how these pieces will communicate with each other where they reflects a unit of the real business. A proper understanding helps in designing the clear interfaces for behaviour and communication between components.2. What are the Twelve-Factors
Twelve factors are defined as a must have attributes for any service to be developed as "Software as a Service". These attributes are well suited for microservices. While developing a microservice we can design and test it against these factors to verify the various aspect of a microservice.Below are the twelve factors which I have copied from Wikipedia for your ease.
# | Factor | Description |
---|---|---|
I | Codebase | There should be exactly one codebase for a deployed service with the codebase being used for many deployments. |
II | Dependencies | All dependencies should be declared, with no implicit reliance on system tools or libraries. |
III | Config | Configuration that varies between deployments should be stored in the environment. |
IV | Backing services | All backing services are treated as attached resources and attached and detached by the execution environment. |
V | Build, release, run | The delivery pipeline should strictly consist of build, release, run. |
VI | Processes | Applications should be deployed as one or more stateless processes with persisted data stored on a backing service. |
VII | Port binding | Self-contained services should make themselves available to other services by specified ports. |
VIII | Concurrency | Concurrency is advocated by scaling individual processes. |
IX | Disposability | Fast startup and shutdown are advocated for a more robust and resilient system. |
X | Dev/Prod parity | All environments should be as similar as possible. |
XI | Logs | Applications should produce logs as event streams and leave the execution environment to aggregate. |
XII | Admin Processes | Any needed admin tasks should be kept in source control and packaged with the application. |
This twelve factors attribute specifies almost most of the thing to be taken care for microservices development but still there are several patterns which can be applied as per business requirement. For example Database per Service pattern also can be used which says each microservice should have it's own database and it must not be shared by other services.
Developing Microservice
As a part of microservice development, we will create a microservice, cloud config server, service registry or discovery server and API gateway. Below architecture depicts the implementation of all components in our example application.Now in further sections we will see the development of all components mentioned in above architecture.
API Gateway
API gateway provides a single entry point to all associated microservices, either directly or through discovery server. It's very useful to access group of services from different providers. There are many other things we can do at API gateway like, auhtentication/authorization, running interceptor codes, filters, logging etc.Discovery Server (Service Registry)
Discovery server provides capability to microservices to register themselves and allows clients to discover these microservices.User Management Service (Microservice)
User management service is a REST based microservice and have below dependencies to run the application.- Cloud config server for configuration management
- RabbitMQ to subscribe the refresh event published by cloud config server
- Discovery server for service registration
- Mongo DB for persistence store
- /users: It displays a welcome message
- /users/{ID}: Provides the details for given user ID.
- /users/create: Creates new user and returns user ID.
- /users/listAll: Returns a list of all existing users.
- Maven dependencies
- Main class (Spring boot class)
- Configuration (bootstrap.yml)
- Domain Object (User)
- Repository Interface
- Service Implementation (Business Logic)
- Rest Service Endpoints
Cloud Config Server (Configuration management)
Cloud Config server is used here to provide the distributed configuration management. Client applications connect to config server and access related configurations. To develop a microservice, configurations must be stored in separate place and available on demand. Using config server microservices can subscribe to config server and pull the latest configurations immediately after any config change in config server.
However in this example we are using only single microservice with API gateway but we can register multiple microservices at a time.
Please refer below post for detailed tutorial and source code.
Spring cloud API Gateway
Please refer below post for detailed tutorial and source code.
Registry/ discovery server using Spring boot and Eureka
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
@EnableDiscoveryClient //required to register itself with eureka discovery server @SpringBootApplication @ComponentScan(basePackages = {"com.ttj"}) public class UserMgmtServiceApplication { public static void main(String[] args) { SpringApplication.run(UserMgmtServiceApplication.class, args); } }
server.port : 8080 spring: application.name: UserManagementService cloud: config: #config server details name: microservices-config uri: http://localhost:8888/ username: config_user password: config_user #rabbit mq to subscribe to refresh events published by config server rabbitmq: host: localhost port: 5672 virtual-host: / username: guest password: guest profiles: active: DEV data: #mongo DB configuraitons mongodb: database: microservice host: localhost port: 27017 repositories: type: auto uri: mongodb://localhost:27017/microservice #Eureka server configurations to register itself eureka: client: serviceUrl: defaultZone: http://localhost:8089/eureka
@Document(collection = "appusers") public class User { @Id private String id; private String userId; private String firstName; private String lastName; private Integer age; public User() {} public User(String userId, String firstName, String lastName, Integer age) { super(); this.userId = userId; this.firstName = firstName; this.lastName = lastName; this.age = age; } //getter methods //setter methods @Override public String toString() { return userId+", "+firstName+", "+lastName+", "+age; } }
public interface UserRepository extends MongoRepository<User, String> { @Query("{ 'userId' : ?0 }") public User findByUserId(String userId); }
@Service public class UserMgmtServiceImpl implements UserMgmtService{ @Autowired UserRepository userRepo; @Override public void saveUser(User user) { userRepo.save(user); } @Override public User findByUserId(String userId) { return userRepo.findByUserId(userId); } @Override public void deleteUser(String userId) { User user = userRepo.findByUserId(userId); userRepo.delete(user); } @Override public ListlistAllUsers(){ return userRepo.findAll(); } }
@RestController @RequestMapping("/users") @RefreshScope public class UserMgmtEndpoint { @Autowired private UserMgmtService userMgmtService; @Value("${message}") private String message; @RequestMapping(method = RequestMethod.GET, produces = "application/json") public String welcome() { return message; } @RequestMapping(value="/{userId}", method = RequestMethod.GET, produces = "application/json") public User findUserById(@PathVariable("userId") String userId) { User user = userMgmtService.findByUserId(userId); return user; } @RequestMapping(value = "/create", method = RequestMethod.POST, consumes = "application/json") public String createUser(@RequestBody User user) { userMgmtService.saveUser(user); return "UserId: "+user.getId(); } @RequestMapping(value = "/listAll", method = RequestMethod.GET, produces = "application/json") public List<User> listUsers() { return userMgmtService.listAllUsers(); } }
Source Code
Complete source code for this microservice is available in below Git location.https://github.com/thetechnojournals/microservices/tree/master/user-mgmt-service
For complete implementation and more details please refer below post on cloud config server.
Cloud config server implementation with example
Running and Testing service
To start the service we need to run it in below order.- Start RabbitMQ and Cloud config server
- Start Discovery server
- Start MongoDB and Microservice
- Start API Gateway
Now you can enter below URL to test the service directly.
http://localhost:8080/users
To test the service through API gateway and discovery server, you need to open below URL in browser.
http://localhost:9999/users/
Both of the above URLs will give you same results.
I am appreciative of this blog's ability to provide information on such an important subject. I discovered other segments here, and I'm excited to put these new instructions to use. test tag perth
ReplyDeleteThanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. how much does it cost to advertise on domain.com.au
ReplyDeleteI really enjoyed your blog posts, thank you
ReplyDeleteBermuda yurtdışı kargo
ReplyDeleteBonaire yurtdışı kargo
Bolivya yurtdışı kargo
Birleşik Arap Emirlikleri yurtdışı kargo
Bhutanya yurtdışı kargo
AE70P
Thank you for writingg this
ReplyDelete