Springcloud 负载均衡之 Ribbon

分布式项目中,为了避免某个服务的集中负载过高导致服务性能的下降或者甚至服务挂掉,需要有一套机制将客户端的请求相对均匀的分发给各个服务,这个机制就可以称之为负载均衡。
负载均衡可以在服务端实现,也可以在客户端实现,在Springcloud中,Ribbon就是作为客户端的负载均衡器来实现负载均衡的, 可以和Eureka服务注册中心一起配合使用,并且在Springcloud中用户可以很方便的自定义负载均衡的算法。

Ribbon实现负载均衡原理

Ribbon实现负载均衡的原理
上图可以描述为:
Eureka Server中注册了各个微服务的实例,Ribbon负载均衡器也注册进Eureka Server中。在接收到客户端的请求时,先通过Eureka Server查找可用的服务列表,将查找到的可用服务发送给Ribbon客户端,Ribbon客户端通过负载均衡算法选择其中的一个服务进行远程调用微服务,将结果返回。

构建Springcloud Ribbon项目

再一次强调,Ribbon是在客户端实现的负载均衡组件,所以构建项目也是在服务消费者的项目中进行。

  1. pom.xml
    在springcloud中,Ribbon通常和Eureka一起使用,需要使用的maven依赖如下:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
  1. application.yml
eureka:
  client:
    register-with-eureka: false    # 自己不作为Eureka的注册中心
    service-url:
      # 指定了Eureka集群的地址
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002 
  1. 主启动类添加相应的注解, 因为Ribbon是注册在Eureka Server中的,所以这里添加@EnableRurekaClient注解即可。
@SpringBootApplication
@EnableEurekaClient
public class App_consumer_dept_80 {
    public static void main(String[] args) {
        SpringApplication.run(App_consumer_dept_80.class, args);
    }
}
  1. 项目中使用RestTemplate来进行微服务的远程调用,需要在RestTemplate的配置类中启用负载均衡机制。
@Configuration
public class BeanConfig {

    @Bean
    @LoadBalanced  // 启用负载均衡
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}
  1. Ribbon是一个负载均衡组件,它和Eureka组合使用时,可以基于微服务的服务名来进行负载均衡调用。通过RestTemplate进行调用时,原本需要写上微服务的访问url, 在使用Ribbon后,可以直接写服务的名字。
@RestController
public class DeptController {

	// 使用RestTemplate进行调用时需要指定服务的url
//    private static final String URL_PREFIX = "http://localhost:8001";

	// 使用Ribbon + Eureka 之后,可以直接通过服务名来进行服务的调用
    private static final String URL_PREFIX = "http://provider-dept";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/dept/{id}")
    public Dept get(@PathVariable("id") Long id) {
    		// 通过RestTemplate进行服务调用
	        return restTemplate.getForObject(URL_PREFIX + "/api/dept/" + id, Dept.class);
    }

  	...
}

发布了8 篇原创文章 · 获赞 3 · 访问量 842

猜你喜欢

转载自blog.csdn.net/weixin_40203134/article/details/87984083