1. 通过Eureka实现服务注册与发现的步骤
- 引入依赖:在每个微服务的
pom.xml
文件中引入Eureka客户端依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 配置Eureka Server地址:在
application.properties
或application.yml
文件中配置Eureka Server的地址。
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
- 启用Eureka客户端:在微服务的主启动类上添加
@EnableEurekaClient
注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class YourServiceApplication {
public static void main(String[] args) {
SpringApplication.run(YourServiceApplication.class, args);
}
}
- 服务发现:当微服务启动后,会自动向配置的Eureka Server注册自己的信息。其他微服务可以通过Eureka Server获取到已注册服务的列表,从而实现服务发现。例如,使用
RestTemplate
结合Eureka进行服务调用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class YourController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/callAnotherService")
public String callAnotherService() {
List<ServiceInstance> instances = discoveryClient.getInstances("another - service - name");
if (instances != null &&!instances.isEmpty()) {
String url = instances.get(0).getUri().toString() + "/api/endpoint";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
return "Service not found";
}
}
2. Eureka Server管理注册服务资源的方式
- 服务注册:Eureka客户端(微服务)在启动时会向Eureka Server发送注册请求,包含自身的一些元数据信息,如服务名称、IP地址、端口号等。Eureka Server接收到注册请求后,会将这些信息存储在一个内部的数据结构(如
ConcurrentHashMap
)中。
- 服务续约:Eureka客户端会定期(默认30秒)向Eureka Server发送心跳请求,以表明自己仍然存活,这个过程称为服务续约。Eureka Server在接收到心跳后,会更新服务实例的最后续约时间。如果在一定时间内(默认90秒)没有收到某个服务实例的心跳,Eureka Server会将该实例从注册列表中剔除,这个过程称为服务过期。
- 服务剔除:除了因服务实例长时间未续约而自动剔除,Eureka Server也提供了手动剔除服务实例的功能。管理员可以通过Eureka Server的管理界面或API手动将某个服务实例从注册列表中移除。
- 自我保护机制:Eureka Server在运行过程中,如果发现大量服务实例同时过期(可能是网络故障等原因导致心跳丢失),为了防止误删服务实例,会开启自我保护机制。在自我保护模式下,Eureka Server不会剔除那些过期的服务实例,而是等待网络恢复或服务实例重新注册。当Eureka Server在一段时间内(默认15分钟)收到的心跳数达到一定比例(默认85%)时,会自动退出自我保护模式。