Service Coordination
Li Wei
Service Coordination
Overview
For the governance of each microservice module, the following questions arise:
What are the three roles in service governance?
- Service Provider (client): Exposes service interfaces for other services to call.
- Service Consumer (client): Calls interfaces provided by other services.
- Registry Center (server): Records and monitors the status of each microservice instance and pushes service‑change information to consumers.
How does a consumer know the provider’s address?
- The service provider registers its information with the registry center at startup; consumers can subscribe to or pull service information from the registry center.
How does one learn about service status changes?
- Providers send heartbeat signals to the registry center to report health. If a heartbeat is abnormal, the registry removes the faulty service and notifies all subscribed consumers.
When a provider has multiple instances, which one should the consumer choose?
- The consumer can use a load‑balancing algorithm to pick one among the instances.
Eureka (Overview)
Basic Introduction
Spring Cloud wraps Netflix’s Eureka module to implement service governance. Eureka follows a C S (Client‑Server) architecture: the Eureka Server acts as the service registry, and other microservices use Eureka clients to connect to the server and maintain heartbeat connections.
- Eureka Server provides registration services: after configuration, each microservice node registers itself with the server. The server’s registry stores information about all available nodes and offers a visual UI.
- Eureka Client accesses the registry: it simplifies interaction with the server and includes a built‑in round‑robin load balancer. After startup, the client sends a heartbeat to the server every 30 seconds (default). If the server does not receive a heartbeat from a node for several cycles (default 90 seconds), it removes that node from the registry.
Server Side
Add the @EnableEurekaServer annotation to the main application class to designate this module as a Eureka registry server. The setup steps are:
- Main application class
- Modify the
pom.xml - Modify
application.yml - Access via browser at
http://localhost:7001
Client Side
Producer
The server’s main class must also include the @EnableEurekaClient annotation, indicating that it is a Eureka client that should register with the Eureka Server.
- Main class:
PaymentMain8001 - Update
pom.xml: add a Eureka‑Client dependency - Create the YAML configuration
- Access via browser at
http://localhost:7001
Consumer
- Main class:
PaymentMain8001 pom.xmlsame as producer- Create the YAML configuration
- Browse to
http://localhost:7001
Cluster Construction
Server Side
High‑availability cluster principle: achieve load balancing and fault tolerance by mutual registration and monitoring.
Multiple Eureka servers each need a unique hostname, and they must register with each other.
Eureka1:
Eureka2:
Main class:
Access
http://eureka7001.com:7001andhttp://eureka7002.com:7002RPC call example:
controller.OrderController
Producer
Build a service cluster for PaymentMain8001.
- Main class
- Write the
ymlfile: change the port and setspring.application.nametocloud-payment-servicefor all instances.
Load Balancing
Consumer‑side controller
Since a producer cluster is already established, load‑balancing can be performed:
- The controller will error if only
PAYMENT_URLis changed, becauseCLOUD-PAYMENT-SERVICEcorresponds to multiple microservices and a rule is needed to decide which port to call. - Use the
@LoadBlancedannotation to giveRestTemplateload‑balancing capability, and add aconfig.ApplicationContextConfigfile.
Service Discovery
Service discovery allows a microservice registered in Eureka to retrieve its own information.
- Add the
@EnableDiscoveryClientannotation to the main class. - Modify the producer’s controller accordingly.
Self‑Protection
Self‑protection mode is used when there is a network partition between clients and the Eureka Server. Once entered, the server protects the information in its registry and stops deleting entries, reflecting the AP side of the CAP theorem (availability and partition tolerance).
If a large number of instances of a microservice disappear within a short period, Eureka activates self‑protection and will not remove the service. This may happen due to temporary network issues, causing “ghost” Eureka nodes, congestion, or latency. To disable self‑protection:
- Server side:
- Client side:
Consul (Overview)
Basic Introduction
Consul is an open‑source distributed service discovery and configuration management system written in Go.
Official site:
- Provides service governance, configuration center, and control bus for microservice systems.
- Based on the Raft consensus algorithm, supports health checks, HTTP and DNS protocols, and WAN clusters across data centers.
- Offers a graphical UI.
After downloading Consul, run the command: consul -version
- Startup command:
- Open a browser at
http://localhost:8500/
Chinese documentation: https://www.springcloud.cc/spring-cloud-consul.html
Server Side
No server‑side code is required.
Client Side
Producer
- Add the Maven dependency.
application.ymlconfiguration.- Main class.
Consumer
application.ymlconfiguration.- Main class: same as producer.
- Configuration class.
- Business controller.
Nacos (Alibaba)
Basic Introduction
Nacos stands for Dynamic Naming and Configuration Service, a platform for dynamic service discovery, configuration management, and service management—essentially Eureka + Config + Bus.
Download: https://github.com/alibaba/nacos/releases
Official site:
Startup command:
## (command omitted)
After the command succeeds, visit http://localhost:8848/nacos. The default username and password are both nacos (http://localhost:8848/nacos%EF%BC%8C%E9%BB%98%E8%AE%A4%E8%B4%A6%E5%8F%B7%E5%AF%86%E7%A0%81%E9%83%BD%E6%98%AF).
Registry Comparison
CAP characteristics: C = Consistency, A = Availability, P = Partition tolerance.
| Registry | CAP Model | Console Management |
|---|---|---|
| Eureka | AP | Supported |
| Zookeeper | CP | Not supported |
| Consul | CP | Supported |
| Nacos | AP | Supported |
Switch mode with curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP.
Registry Principles
In large microservice projects, many service providers exist, so a registry center is introduced to manage them. The relationships are:
- Providers register their service info (name, IP, port) with the registry at startup.
- Consumers subscribe to the registry to obtain a list of instances for a desired service (a service may have multiple instances).
- Consumers perform their own load balancing on the instance list and pick one.
- Consumers invoke the selected instance.
When a provider instance crashes or a new instance starts, how does the consumer learn?
- Providers periodically send heartbeat requests to the registry to report health.
- If the registry stops receiving heartbeats for a long time, it assumes the instance is down and removes it from the list.
- New instances register themselves, and the registry records them.
- When the service list changes, the registry proactively notifies microservices to update their local caches.
Basic Usage
Register a service with Nacos:
- Add the Maven dependency.
application.ymlconfiguration.- Main class annotated with
@EnableDiscoveryClient. - Management console service.
Consumer pulls services from Nacos:
- Add the dependency in
pom.xml. application.ymlconfiguration.- Main class.
- Business class.
Configuration Center
Problem Thinking
Configuration files in microservices often cause issues:
- Gateway routes are hard‑coded; any change requires a service restart.
- Business parameters are hard‑coded; each change needs a restart.
- Many microservices duplicate the same configuration, raising maintenance cost.
A unified configuration management service can solve these problems. Nacos not only acts as a registry but also provides configuration management.
Shared configurations stored in Nacos can be modified via the Nacos console; changes are pushed to the relevant microservices and take effect without a restart (hot‑update). Since gateway routing is also configuration, dynamic routing can be achieved without restarting the gateway.
Shared Configuration
Extract common configuration into Nacos and manage it centrally, eliminating duplication. Steps:
- Add shared configuration in Nacos.
- Microservices pull the configuration.
Add shared configuration: write the config file into Nacos and treat Nacos as a config server. In Nacos, the full format for DataId is **${prefix}-${spring.profiles.active}.${file-extension}**
prefixdefaults to the value ofspring.application.name; it can also be set via the propertyspring.cloud.nacos.config.prefix.spring.profiles.activeis the profile for the current environment; if empty, thedataIdformat becomes${prefix}.${file-extension}.file-exetensionspecifies the data format of the configuration content; it can be set viaspring.cloud.nacos.config.file-extension. Currently onlypropertiesandyaml(notyml) are supported.
Procedure:
- In the Nacos console
配置管理->配置列表->点击+, create a new configuration. - Fill out the form that appears.
Detailed configuration example:
Note that JDBC parameters are not hard‑coded. For example:
- Database IP: defaulted to
192.168.150.101via${hm.db.host:192.168.150.101}, overridable with${hm.db.host}. - Database port: defaulted to
3306via${hm.db.port:3306}, overridable with${hm.db.port}. - Database name: set via
${hm.db.database}(no default).
Pulling Shared Configuration
Next, microservices retrieve the shared configuration and merge it with the local application.yaml configuration to complete context initialization.
Important: Nacos configuration is processed during bootstrap initialization (SpringCloud上下文(ApplicationContext)), which occurs before Spring Boot loads application.yaml. At that early stage the application.yaml file has not been read, so the Nacos address is unknown. Spring Cloud first reads a file named bootstrap.yaml (or bootstrap.properties). By placing the Nacos address in bootstrap.yaml, the bootstrap phase can fetch Nacos configuration.
Therefore, integrating Nacos configuration management follows these steps:
- Add the Maven dependency.
- Create a
bootstrap.yamlundersrc/main/resourcesfor global configuration. - Restart the service for the configuration to take effect.
Hot Update
Business parameters often need on‑the‑fly adjustments. To avoid repackaging and restarting, use Nacos’s hot‑update capability.
Steps:
Add a configuration in Nacos. Using the name
cart-service.yamlmakes it shareable across bothdevandlocalenvironments.- Submit the configuration; it appears in the console.
In the microservice, read the configuration:
- Create a property‑binding class in the relevant service.
- Use the class in business code; after a restart, hot updates will be applied automatically.
Cluster Architecture
Refer to the official documentation for deployment. Nacos supports three modes:
- Standalone: for testing or single‑node use.
- Cluster: for production, ensuring high availability.
- Multi‑cluster: for multi‑data‑center scenarios.
Cluster deployment docs:
By default, Nacos uses an embedded database derby for storage. After a restart, configuration files persist, but multiple Nacos nodes each have their own embedded DB, leading to consistency issues. Therefore, Nacos adopts a centralized storage approach for clustering, currently supporting only MySQL.
Switching to MySQL on Windows:
- In the
confdirectory of the Nacos installation, locate and run the scriptnacos-mysql.sql. - Edit
conffileapplication.propertiesto add the following data source configuration. - Restart Nacos; you will see a fresh, empty records page.
Linux reference:
Differences Between Nacos and Eureka
Nacos service instances come in two types:
- Temporary instance (default): removed from the list if down for a certain period.
- Non‑temporary (permanent) instance: stays in the list even if down.
Configure a service as a permanent instance:
(configuration snippet omitted)
Overall, Nacos and Eureka share a similar architecture (registration, pulling, heartbeat), but there are notable differences:
Commonalities
- Both support service registration and pulling.
- Both use provider heartbeats for health checking.
Differences
- Nacos can actively probe provider status: temporary instances use heartbeat, non‑temporary instances use active detection.
- Temporary instances are removed on heartbeat failure; non‑temporary instances are not.
- Nacos pushes service‑list change notifications, making updates more timely.
- Nacos clusters default to AP; when non‑temporary instances exist, they switch to CP. Eureka operates in AP mode.
Zookeeper
Basic Introduction
Framework Characteristics
Zookeeper is a sub‑project of Apache Hadoop that provides coordination services for distributed systems; it offers a hierarchical namespace (a tree‑like directory service).
Official site:
Designed using the observer pattern, Zookeeper stores and manages shared data, registers observers, and notifies them when data changes.
- Consists of one Leader and multiple Followers.
- The cluster remains operational as long as a majority of nodes are alive, so an odd number of servers is recommended.
- Globally consistent data: each server holds the same data replica; clients see identical data regardless of which server they connect to.
- Requests are processed in order; a single client’s requests are executed sequentially.
- Atomic updates: a data change either fully succeeds or fails.
- Real‑time: clients can read the latest data within a bounded time.
- Heartbeat detection: Zookeeper periodically sends a request (maintaining a long‑lived socket) to each service provider.
Application Scenarios
Zookeeper’s main functions include unified naming, configuration management, cluster management, dynamic server registration/deregistration, soft load balancing, distributed locks, etc.
- In distributed environments, a unified naming service simplifies identification (e.g., domain names are easier to handle than raw IPs).
(content truncated)
Originally written by Li Wei (李唯_) and published in Chinese on 后端技术栈全书 (Full-Stack Backend Engineering). Translated and adapted for DriftSeas with permission.