簡介
-
什麼是負載均衡?
負載均衡是分佈式架構中不可或缺的一個組件,其意義在於通過一定的規則或者算法去將請求分攤到各個服務提供者。 -
Ribbon是一個客戶端的負載均衡器,它提供一系列讓你控制HTTP和TCP客戶端的能力。
以下示例均基於SpringCloud的Greenwich.SR1版本,且需要依賴到之前介紹Eureka的文章
基礎依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<!-- 使用Eureka來配合Ribbon -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
Ribbon
需要測試Ribbon的功能,需要以下幾個步驟。
- 先運行Eureka-Server,啓動註冊中心。
- 再運行兩個不同端口(6603、6604)的Eureka-Client。
需要改一下之前的代碼,在 /hello 接口中增加端口的輸出來區分服務。
@Value("\${server.port}")
var port: String? = null
@RequestMapping("/hello")
fun hello(@RequestParam("name") name: String): String {
return "response from $port: hello $name."
}
- 配置啓動Ribbon測試應用
因爲我們這裏需要依賴到Eureka,所以要指定註冊中心的地址。
application.yml
server:
port: 6605
eureka:
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://localhost:6600/eureka/
spring:
application:
name: ribbon-client
在啓動類中,要增加 @EnableDiscoveryClient 註解。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
class RibbonClientStarter
fun main(args: Array<String>) {
runApplication<RibbonClientStarter>(*args)
}
啓動之後,打開 http://localhost:6600 可以看到現在啓動的服務。
EUREKA-CLIENT UP (2) - 192.168.1.135:eureka-client:6603 , 192.168.1.135:eureka-client:6604
RIBBON-CLIENT UP (1) - 192.168.1.135:ribbon-client:6605
- 創建一個Controller去調用Eureka-Client的服務。
先配置創建一個RestTemplate的Bean去負責調用。
@Configuration
class RestTemplateConfiguration {
// 使用 @LoadBalance 開啓負載均衡。
@Bean
@LoadBalanced
fun restTemplate(): RestTemplate {
return RestTemplate()
}
}
再在Controller中使用RestTemplate。
@RestController
class DemoController {
@Autowired
lateinit var restTemplate: RestTemplate
@RequestMapping("/hello")
fun hello(@RequestParam("name") name: String): String? {
// 其中 EUREKA-CLIENT 爲application.yml中的應用名的大寫形式,也是註冊中心中顯示的名字。
// hello 則爲服務提供的接口名。
return restTemplate.getForObject("http://EUREKA-CLIENT/hello?name=$name", String::class.java)
}
}
多次訪問 http://localhost:6605/hello?name=czb1n,會輪流顯示:response from 6603: hello czb1n.
和 response from 6604: hello czb1n.
其他
示例代碼地址: https://github.com/czb1n/learn-spring-cloud-with-kotlin