In a microservice architecture, services often need to communicate with each other. This is typically done using RestTemplate for exchanging HTTP requests. However, hardcoding IP addresses in these interactions leads to two major issues:
- Load Imbalance: When multiple instances of a service provider are available, hardcoding the IP address of a single instance causes the other instances to remain idle. This leads to uneven distribution of traffic, with one instance bearing the brunt of the load.
- Single Point of Failure: If the hardcoded service provider instance goes offline, the microservice loses access to the service, as it cannot dynamically switch to other available instances. This results in reduced reliability and increased downtime.
To address these challenges, this project leverages Spring Cloud Alibaba Nacos for dynamic service discovery and registration. Nacos simplifies the process of managing microservices by providing a centralized service registry and a robust configuration management system.
Based on the above diagram, Nacos allows service providers to register themselves at runtime. Instead of relying on hardcoded IP addresses, services are identified by their logical names. Nacos tracks all available instances of each service, ensuring that service consumer requests are dynamically routed to healthy instances.
.
├── cart-service
│ ├── src
│ │ ├── main
| | | ├── java/com/example
| | | | ├── config
| | | | ├── controller
| | | | ├── mapper
| | | | ├── pojo
| | | | ├── service
| | | | └── CartServiceApplication.java
| | | └── resources
│ │ └── test
│ └── pom.xml
|
├── item-service
│ ├── src
│ │ ├── main
| | | ├── java/com/example
| | | | ├── controller
| | | | ├── mapper
| | | | ├── pojo
| | | | ├── service
| | | | └── ItemServiceApplication.java
| | | └── resources
│ │ └── test
│ └── pom.xml
|
├── data
| └── init.sql
|
├── docker-compose.yml
|
├── pom.xml
|
└── README.md
- Postman
- IntelliJ IDEA
- Docker Desktop
- MySQL Workbench (optional)
- Clone the repository
git clone https://github.com/ongdisheng/Spring-Cloud-Nacos.git
- Spin up MySQL and Nacos using Docker Compose
cd Spring-Cloud-Nacos
docker-compose up -d
- Execute microservice applications
Ensure that ItemServiceApplication2 is started on a port that is not currently in use by other services to avoid port conflicts
- Visit http://localhost:8848/nacos to view the registered item service providers using the credentials:
- Username: nacos
- Password: nacos
- Simulate the communication between the Cart microservice and the Item microservice using Postman