Spring Cloud - Ribbon负载均衡

在上一篇Spring Cloud - Eureka服务注册与发现中消费方调用提供方的Http服务时,通过硬编码的方式显式地指定了请求的URLhttp://localhost:20001/test,这样很不方便,而且涉及到负载均衡的时候就很难处理了。

对于大型应用,单机部署一定会成为流量瓶颈,集群与负载均衡必不可少。传统方式的负载均衡会使用到F5等硬件设备,或者使用Proxy方式解决。而Spring Cloud以另外一种方式(将负载均衡功能集成到服务消费方的进程内)实现了软负载均衡,这一功能在Srping Cloud中是由Ribbon子项目实现的。

这篇文章介绍通过RestTemplate+Ribbon的方式实现负载均衡。

系统架构图:

Spring Cloud - Ribbon负载均衡_第1张图片
Ribbon负载均衡.png

Eureka中使用Ribbon的具体实现如下(kotlin版)

1.引入Ribbon依赖

首先在服务消费方引入Ribbon的依赖,因为负载均衡是由Ribbon提供支持的,并且负载均衡的策略是在调用方实现的。

compile('org.springframework.cloud:spring-cloud-starter-netflix-ribbon:2.0.0.RELEASE')
2.使用@LoadBalanced注解

Spring Cloud中提供了@LoadBalanced注解,在启动应用的时候通过@Bean实例化RestTemplate,并且添加@LoadBalanced,在后续使用RestTemplate时,就支持负载均衡了。

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.client.RestTemplate
import org.springframework.cloud.client.loadbalancer.LoadBalanced
import org.springframework.context.annotation.Bean

@SpringBootApplication
class EurekaClientConsumerApplication {
    @Bean
    @LoadBalanced
    fun restTemplate(): RestTemplate {
        return RestTemplate()
    }
}

fun main(args: Array) {
    runApplication(*args)
}
3.改造请求URL

然后修改之前调用的请求URL,用服务提供方application.yml文件中配置的spring.application.name属性值替换host:port即可。

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
class TestController {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    @GetMapping("/test")
    fun test(): String? {
        return restTemplate.getForEntity("http://eureka-client-provider/test", String::class.java).body
    }
}

启动多个服务提供方实例,服务消费方从服务注册中心获取到服务列表后,多次发起请求时会通过RestTemplate以轮询方式依次请求的不同的服务提供方。对于开发者而言,需要做的非常简单,仅需要指定@LoadBalanced即可,一个注解完成了一系列复杂的负载均衡策略内部实现,而这些复杂的处理对开发者是透明的。

你可能感兴趣的:(Spring Cloud - Ribbon负载均衡)