面试题答案
一键面试技术原理
- Eureka Server 高可用:多个 Eureka Server 实例相互注册,形成对等网络。每个实例都保存所有服务的注册表信息,当某个实例故障时,其他实例仍能提供服务注册与发现功能。
- 负载均衡:服务消费者从 Eureka Server 获取服务列表后,需要在多个服务实例间进行负载均衡调用。Spring Cloud Ribbon 是一个客户端负载均衡器,它从 Eureka Server 拉取服务实例列表,并根据一定的负载均衡算法(如轮询、随机等)选择一个实例进行调用。
具体实现步骤
- 添加依赖:在服务消费者的
pom.xml
文件中添加 Eureka 客户端和 Ribbon 的依赖。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 配置 Eureka Server:在服务消费者的
application.yml
文件中配置 Eureka Server 地址。
eureka:
client:
service-url:
defaultZone: http://eureka1:8761/eureka/,http://eureka2:8761/eureka/
这里配置了多个 Eureka Server 地址,服务消费者会向这些地址注册自己并获取服务列表。
3. 启用 Eureka 客户端:在服务消费者的主启动类上添加 @EnableEurekaClient
注解,开启 Eureka 客户端功能。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
- 使用 Ribbon 进行负载均衡调用:通过
RestTemplate
结合 Ribbon 实现负载均衡调用。首先,在配置类中创建RestTemplate
并添加@LoadBalanced
注解。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
然后,在需要调用服务的地方注入 RestTemplate
并通过服务名进行调用。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer")
public String callService() {
return restTemplate.getForObject("http://provider-service/hello", String.class);
}
}
这里 provider-service
是服务提供者在 Eureka Server 上注册的服务名,Ribbon 会根据负载均衡算法从 Eureka Server 获取的服务实例列表中选择一个实例进行调用。