MST

星途 面试题库

面试题:微服务架构下Spring Cloud资源管理之中等难度题

在Spring Cloud微服务架构中,如何通过Eureka实现服务的注册与发现,并且说明Eureka Server是如何管理这些注册服务的资源的?
39.2万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

1. 通过Eureka实现服务注册与发现的步骤

  1. 引入依赖:在每个微服务的pom.xml文件中引入Eureka客户端依赖。
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  1. 配置Eureka Server地址:在application.propertiesapplication.yml文件中配置Eureka Server的地址。
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  1. 启用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);
    }
}
  1. 服务发现:当微服务启动后,会自动向配置的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管理注册服务资源的方式

  1. 服务注册:Eureka客户端(微服务)在启动时会向Eureka Server发送注册请求,包含自身的一些元数据信息,如服务名称、IP地址、端口号等。Eureka Server接收到注册请求后,会将这些信息存储在一个内部的数据结构(如ConcurrentHashMap)中。
  2. 服务续约:Eureka客户端会定期(默认30秒)向Eureka Server发送心跳请求,以表明自己仍然存活,这个过程称为服务续约。Eureka Server在接收到心跳后,会更新服务实例的最后续约时间。如果在一定时间内(默认90秒)没有收到某个服务实例的心跳,Eureka Server会将该实例从注册列表中剔除,这个过程称为服务过期。
  3. 服务剔除:除了因服务实例长时间未续约而自动剔除,Eureka Server也提供了手动剔除服务实例的功能。管理员可以通过Eureka Server的管理界面或API手动将某个服务实例从注册列表中移除。
  4. 自我保护机制:Eureka Server在运行过程中,如果发现大量服务实例同时过期(可能是网络故障等原因导致心跳丢失),为了防止误删服务实例,会开启自我保护机制。在自我保护模式下,Eureka Server不会剔除那些过期的服务实例,而是等待网络恢复或服务实例重新注册。当Eureka Server在一段时间内(默认15分钟)收到的心跳数达到一定比例(默认85%)时,会自动退出自我保护模式。