深入學(xué)習(xí)Spring Cloud-Ribbon
ribbon簡介
Ribbon 是 Netflix 發(fā)布的開源項(xiàng)目,主要功能是提供客戶端的 軟件負(fù)載均衡算法 ,將 Netflix 的中間層服務(wù)連接在一起。Ribbon 客戶端組件提供一系列完善的配置項(xiàng)如連接超時,重試等。簡單的說,就是在配置文件中列出Load Balancer(簡稱LB)后面所有的機(jī)器,Ribbon 會自動的幫助你基于某種規(guī)則(如簡單輪詢,隨機(jī)連接等)去連接這些機(jī)器。我們也很容易使用 Ribbon 實(shí)現(xiàn)自定義的負(fù)載均衡算法。
ribion=負(fù)載均衡+重試

ribbon的工作步驟:
第一步先選擇 EurekaServer ,它優(yōu)先選擇在同一個區(qū)域內(nèi)負(fù)載較少的server。 第二步再根據(jù)用戶指定的策略,在從server取到的服務(wù)注冊列表中選擇一個地址。 其中Ribbon提供了多種策略:比如輪詢、隨機(jī)和根據(jù)響應(yīng)時間加權(quán)。

創(chuàng)建spring ribbon項(xiàng)目
第一步:新建spring項(xiàng)目

第二步:添加Eureka Discovery Client,Spring Web依賴

第三步:添加sp01-commons工具API依賴;eureka-client 中已經(jīng)包含 ribbon 依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.tedu</groupId>
<artifactId>sp06-ribbon</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sp06-ribbon</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.tedu</groupId>
<artifactId>sp01-commons</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
第四步:添加yml配置
spring: application: name: ribbon #服務(wù)器命名 server: port: 3001 # 設(shè)置服務(wù)器端口號 # 配置添加注冊中心集群 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
遠(yuǎn)程調(diào)用RestTemplate
RestTemplate 是SpringBoot提供的一個Rest遠(yuǎn)程調(diào)用工具。
類似于 HttpClient,可以發(fā)送 http 請求,并處理響應(yīng)。RestTemplate簡化了Rest API調(diào)用,只需要使用它的一個方法,就可以完成請求、響應(yīng)、Json轉(zhuǎn)換
方法:
- getForObject(url, 轉(zhuǎn)換的類型.class, 提交的參數(shù))
- postForObject(url, 協(xié)議體數(shù)據(jù), 轉(zhuǎn)換的類型.class)
RestTemplate 和 Dubbo 遠(yuǎn)程調(diào)用的區(qū)別:
RestTemplate:
http調(diào)用
效率低
Dubbo:
RPC調(diào)用,Java的序列化
效率高
第一步:創(chuàng)建RestTemplate實(shí)例
RestTemplate 是用來調(diào)用其他微服務(wù)的工具類,封裝了遠(yuǎn)程調(diào)用代碼,提供了一組用于遠(yuǎn)程調(diào)用的模板方法,例如: getForObject() 、 postForObject() 等
package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {
//創(chuàng)建 RestTemplate 實(shí)例,并存入 spring 容器
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
}
第二步:創(chuàng)建RibbonController
package cn.tedu.sp06.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
@RestController
public class RibbonController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
//向指定微服務(wù)地址發(fā)送 get 請求,并獲得該服務(wù)的返回結(jié)果
//{1} 占位符,用 orderId 填充
return rt.getForObject("http://localhost:8001/{1}", JsonResult.class, orderId);
}
@PostMapping("/item-service/decreaseNumber")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
//發(fā)送 post 請求
return rt.postForObject("http://localhost:8001/decreaseNumber", items, JsonResult.class);
}
/
@GetMapping("/user-service/{userId}")
public JsonResult<User> getUser(@PathVariable Integer userId) {
return rt.getForObject("http://localhost:8101/{1}", JsonResult.class, userId);
}
@GetMapping("/user-service/{userId}/score")
public JsonResult addScore(
@PathVariable Integer userId, Integer score) {
return rt.getForObject("http://localhost:8101/{1}/score?score={2}", JsonResult.class, userId, score);
}
/
@GetMapping("/order-service/{orderId}")
public JsonResult<Order> getOrder(@PathVariable String orderId) {
return rt.getForObject("http://localhost:8201/{1}", JsonResult.class, orderId);
}
@GetMapping("/order-service")
public JsonResult addOrder() {
return rt.getForObject("http://localhost:8201/", JsonResult.class);
}
}
第三步:啟動服務(wù),進(jìn)行測試
http://localhost:3001/item-service/35
等。。
ribbon負(fù)載均衡

第一步:RestTemplate設(shè)置@LoadBalanced
@LoadBalanced 負(fù)載均衡注解,會對 RestTemplate 實(shí)例進(jìn)行封裝,創(chuàng)建動態(tài)代理對象,并切入(AOP)負(fù)載均衡代碼,把請求分發(fā)到集群中的服務(wù)器
package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class Sp06RibbonApplication {
@LoadBalanced //負(fù)載均衡注解
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
}
第二步:訪問路徑設(shè)置為id
package cn.tedu.sp06.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
@RestController
public class RibbonController {
@Autowired
private RestTemplate rt;
@GetMapping("/item-service/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
//這里服務(wù)器路徑用 service-id 代替,ribbon 會向服務(wù)的多臺集群服務(wù)器分發(fā)請求
return rt.getForObject("http://item-service/{1}", JsonResult.class, orderId);
}
@PostMapping("/item-service/decreaseNumber")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
return rt.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
}
/
@GetMapping("/user-service/{userId}")
public JsonResult<User> getUser(@PathVariable Integer userId) {
return rt.getForObject("http://user-service/{1}", JsonResult.class, userId);
}
@GetMapping("/user-service/{userId}/score")
public JsonResult addScore(
@PathVariable Integer userId, Integer score) {
return rt.getForObject("http://user-service/{1}/score?score={2}", JsonResult.class, userId, score);
}
/
@GetMapping("/order-service/{orderId}")
public JsonResult<Order> getOrder(@PathVariable String orderId) {
return rt.getForObject("http://order-service/{1}", JsonResult.class, orderId);
}
@GetMapping("/order-service")
public JsonResult addOrder() {
return rt.getForObject("http://order-service/", JsonResult.class);
}
}
第三步:訪問測試,ribbon 會把請求分發(fā)到 8001 和 8002 兩個服務(wù)端口上
http://localhost:3001/item-service/34 ribbon重試

第一步:添加spring-retry依賴
<dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
第二步:application.yml 配置 ribbon 重試
# 06項(xiàng)目用來測試遠(yuǎn)程調(diào)用和ribbon工具 # 等功能測試完成后,直接刪除 spring: application: name: ribbon server: port: 3001 # 連接eureka,從eureka發(fā)現(xiàn)其他服務(wù)的地址 eureka: client: service-url: defaultZone: http://eureka1:2001/eureka,http://eureka2:2002/eureka #配置ribbon 重試次數(shù) ribbon: # 次數(shù)參數(shù)沒有提示,并且會有黃色警告 # 重試次數(shù)越少越好,一般建議用0,1 MaxAutoRetries: 1 MaxAutoRetriesNextServer: 2
第三步:設(shè)置 RestTemplate 的請求工廠的超時屬性
package cn.tedu.sp06;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class Sp06RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
/**
* 創(chuàng)建RestTemplate實(shí)例
* 放入spring容器
* @LoadBalanced-對RestTemplate進(jìn)行增強(qiáng),封裝RestTemplate,添加負(fù)載均衡功能
*/
@LoadBalanced
@Bean public RestTemplate restTemplate(){
//設(shè)置調(diào)用超時時間,超時后認(rèn)為調(diào)用失敗
SimpleClientHttpRequestFactory f =
new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);//建立連接等待時間
f.setReadTimeout(1000);//連接建立后,發(fā)送請求后,等待接收響應(yīng)的時間
return new RestTemplate(f);
}
}
第四步:ItemController 添加延遲代碼
package cn.tedu.sp02.item.controller;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
//配置文件 application.yml中的server.port=8001注入到這個變量
//是為了后面做負(fù)載均衡測試,可以直接看到調(diào)用的是那個服務(wù)器
@Value("${server.port}")
private int port;
//獲取訂單的商品列表
@GetMapping("/{orderId}")
public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
log.info("server.port="+port+", orderId="+orderId);
//模擬延遲代碼
if (Math.random()<0.9){
long t = new Random().nextInt(5000);
log.info("延遲:"+t);
Thread.sleep(t);
}
List<Item> items = itemService.getItems(orderId);//根據(jù)訂單id獲取商品列表
return JsonResult.ok(items).msg("port="+port);
}
//減少商品庫存
/**
* @RequestBody 完整接收請求協(xié)議體中的數(shù)據(jù)
* @param items
* @return
*/ @PostMapping("/decreaseNumber")
public JsonResult decreaseNumber(@RequestBody List<Item> items) {
for (Item item : items){
log.info("減少商品庫存:"+item );
}
itemService.decreaseNumbers(items);
return JsonResult.ok();
}
}
第五步:測試 ribbon 重試機(jī)制
通過 ribbon 訪問 item-service,當(dāng)超時,ribbon 會重試請求集群中其他服務(wù)器
http://localhost:3001/item-service/35
到此這篇關(guān)于深入學(xué)習(xí)Spring Cloud-Ribbon的文章就介紹到這了,更多相關(guān)Spring Cloud-Ribbon內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 淺談SpringCloud之Ribbon詳解
- 淺談Spring Cloud Netflix-Ribbon灰度方案之Zuul網(wǎng)關(guān)灰度
- springcloud中Ribbon和RestTemplate實(shí)現(xiàn)服務(wù)調(diào)用與負(fù)載均衡
- SpringCloud 2020-Ribbon負(fù)載均衡服務(wù)調(diào)用的實(shí)現(xiàn)
- SpringCloud Netflix Ribbon源碼解析(推薦)
- Spring Cloud Ribbon配置詳解
- SpringCloud手寫Ribbon實(shí)現(xiàn)負(fù)載均衡
- SpringCloud 服務(wù)負(fù)載均衡和調(diào)用 Ribbon、OpenFeign的方法
- Springcloud ribbon負(fù)載均衡算法實(shí)現(xiàn)
- 詳解SpringCloud Ribbon 負(fù)載均衡通過服務(wù)器名無法連接的神坑
- SpringCloud Ribbon 負(fù)載均衡的實(shí)現(xiàn)
- Spring Cloud調(diào)用Ribbon的步驟
相關(guān)文章
Java實(shí)戰(zhàn)之基于TCP實(shí)現(xiàn)簡單聊天程序
這篇文章主要為大家詳細(xì)介紹了如何在Java中基于TCP實(shí)現(xiàn)簡單聊天程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
JavaWeb 實(shí)現(xiàn)多個文件壓縮下載功能
文件下載時,我們可能需要一次下載多個文件,批量下載文件時,需要將多個文件打包為zip,然后再下載。本文給大家分享實(shí)現(xiàn)思路及具體實(shí)現(xiàn)代碼,對javaweb實(shí)現(xiàn)文件壓縮下載功能感興趣的朋友一起學(xué)習(xí)吧2017-07-07
MyBatis實(shí)現(xiàn)動態(tài)查詢、模糊查詢功能
這篇文章主要介紹了MyBatis實(shí)現(xiàn)動態(tài)查詢、模糊查詢功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06
Java中轉(zhuǎn)義字符反斜杠\的代替方法及repalceAll內(nèi)涵解析
這篇文章主要介紹了Java中轉(zhuǎn)義字符反斜杠\的代替方法及repalceAll內(nèi)涵解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Java實(shí)現(xiàn)發(fā)送手機(jī)短信語音驗(yàn)證功能代碼實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)發(fā)送手機(jī)短信語音驗(yàn)證功能代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09
springboot+angular4前后端分離 跨域問題解決詳解
這篇文章主要介紹了springboot+angular4前后端分離 跨域問題解決詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09
Spring Boot使用模板freemarker的示例代碼
本篇文章主要介紹了Spring Boot使用模板freemarker的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
使用springboot跳轉(zhuǎn)到指定頁面和(重定向,請求轉(zhuǎn)發(fā)的實(shí)例)
這篇文章主要介紹了使用springboot跳轉(zhuǎn)到指定頁面和(重定向,請求轉(zhuǎn)發(fā)的實(shí)例),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Spring?Security密碼解析器PasswordEncoder自定義登錄邏輯
這篇文章主要為大家介紹了Spring?Security密碼解析器PasswordEncoder自定義登錄邏輯示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

