📢 This article was translated by gemini-3-flash-preview
Before diving into service registries, let’s define the concepts of Providers and Consumers.
Providers and Consumers
Service Provider: The service being called by other microservices during a business transaction (provides interfaces/APIs).
Service Consumer: The service calling other microservices during a business transaction (calls interfaces/APIs).
These roles are relative: a single service can act as both a provider and a consumer simultaneously.
Eureka
If you have multiple providers, how does a consumer find them or know if they are healthy?
On startup, microservices register their information with Eureka. Consumers then pull this provider info from Eureka to perform remote calls. Microservices send a heartbeat to Eureka every 30 seconds to confirm they are still alive. Eureka updates its service list accordingly and evicts unhealthy instances.
If multiple service providers are available, the consumer uses a load-balancing algorithm to pick one from the list.
Setup
Create a new Maven Module and add the dependency:
1
2
3
4
| <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
|
Create the startup class:
1
2
3
4
5
6
7
| @EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
|
Configuration file:
1
2
3
4
5
6
7
8
9
| server:
port: 7995
spring:
application:
name: eureka-server
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:7995/eureka
|
Service Registration
Add the dependency:
1
2
3
4
| <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
|
Add configuration:
1
2
3
4
5
6
7
| spring:
application:
name: userService
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:7995/eureka
|
Usage
Register the bean:
1
2
3
4
5
| @Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
|
Change the target URL from a hardcoded hostname to the service name:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| @Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1. Query order
Order order = orderMapper.findById(orderId);
// 2. Query user
// String url = "http://localhost:8081/user/" + order.getUserId();
String url = "http://userService/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
// 3. Encapsulate user info
order.setUser(user);
// 4. Return
return order;
}
}
|