MST

星途 面试题库

面试题:微服务架构中基于Spring Cloud如何实现服务的负载均衡调用

在基于Spring Cloud的微服务架构里,阐述使用Ribbon或Feign实现服务负载均衡调用的原理及具体配置步骤。
19.8万 热度难度
后端开发微服务架构

知识考点

AI 面试

面试题答案

一键面试

Ribbon

  1. 原理
    • Ribbon是一个客户端负载均衡器。它集成在客户端(服务消费者)中,从Eureka Server获取服务实例列表。
    • Ribbon会在本地维护一个负载均衡算法,比如轮询(Round Robin)、随机(Random)等。当客户端发起对服务的调用时,Ribbon会根据配置的负载均衡算法从服务实例列表中选择一个实例进行调用。
  2. 具体配置步骤
    • 引入依赖:在服务消费者的pom.xml中引入Ribbon依赖。如果使用Spring Cloud Netflix,一般spring - cloud - starter - netflix - eureka - client依赖中已经包含了Ribbon,无需单独引入。
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring - cloud - starter - netflix - ribbon</artifactId>
    </dependency>
    
    • 配置服务调用:在application.yml中配置服务名及负载均衡相关属性,例如:
    service - name:
        ribbon:
            NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 配置负载均衡规则为随机
    
    • 使用RestTemplate调用:在代码中使用RestTemplate进行服务调用,RestTemplate会被Ribbon自动拦截,实现负载均衡调用。
    @Autowired
    private RestTemplate restTemplate;
    public String callService() {
        return restTemplate.getForObject("http://service - name/path", String.class);
    }
    
    • 开启负载均衡:在Spring Boot启动类上添加@LoadBalanced注解,使RestTemplate具备负载均衡能力。
    @SpringBootApplication
    public class ConsumerApplication {
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
        public static void main(String[] args) {
            SpringApplication.run(ConsumerApplication.class, args);
        }
    }
    

Feign

  1. 原理
    • Feign是一个声明式的Web服务客户端。它基于Ribbon实现负载均衡。
    • Feign通过接口的方式定义服务调用,使用注解来配置请求的方法、路径等信息。当调用接口方法时,Feign会构建请求,通过Ribbon从服务实例列表中选择一个实例进行调用。
  2. 具体配置步骤
    • 引入依赖:在服务消费者的pom.xml中引入Feign依赖。
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring - cloud - starter - openfeign</artifactId>
    </dependency>
    
    • 开启Feign:在Spring Boot启动类上添加@EnableFeignClients注解,开启Feign功能。
    @SpringBootApplication
    @EnableFeignClients
    public class ConsumerApplication {
        public static void main(String[] args) {
            SpringApplication.run(ConsumerApplication.class, args);
        }
    }
    
    • 定义Feign接口:创建一个接口,使用Feign的注解来定义服务调用。例如:
    @FeignClient("service - name")
    public interface ServiceClient {
        @GetMapping("/path")
        String callService();
    }
    
    • 使用Feign接口调用:在业务代码中注入Feign接口并调用其方法。
    @Autowired
    private ServiceClient serviceClient;
    public String callRemoteService() {
        return serviceClient.callService();
    }
    
    • 配置负载均衡规则:同Ribbon,在application.yml中配置服务名及负载均衡相关属性,例如:
    service - name:
        ribbon:
            NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 配置负载均衡规则为随机