欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

深入學(xué)習(xí)Spring Cloud-Ribbon

 更新時(shí)間:2021年03月03日 10:52:41   投稿:mrr  
這篇文章主要介紹了Spring Cloud-Ribbon的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友一起看看吧

ribbon簡介

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

ribion=負(fù)載均衡+重試

ribbon的工作步驟:

第一步先選擇 EurekaServer ,它優(yōu)先選擇在同一個(gè)區(qū)域內(nèi)負(fù)載較少的server。 第二步再根據(jù)用戶指定的策略,在從server取到的服務(wù)注冊(cè)列表中選擇一個(gè)地址。 其中Ribbon提供了多種策略:比如輪詢、隨機(jī)和根據(jù)響應(yīng)時(shí)間加權(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ù)器端口號(hào)
 
# 配置添加注冊(cè)中心集群 
eureka:
 client:
  service-url:
   defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka

遠(yuǎn)程調(diào)用RestTemplate

RestTemplate 是SpringBoot提供的一個(gè)Rest遠(yuǎn)程調(diào)用工具。

類似于 HttpClient,可以發(fā)送 http 請(qǐng)求,并處理響應(yīng)。RestTemplate簡化了Rest API調(diào)用,只需要使用它的一個(gè)方法,就可以完成請(qǐng)求、響應(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 請(qǐng)求,并獲得該服務(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 請(qǐng)求
    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);
  }
}

第三步:啟動(dòng)服務(wù),進(jìn)行測(cè)試

http://localhost:3001/item-service/35

等。。

ribbon負(fù)載均衡

第一步:RestTemplate設(shè)置@LoadBalanced

@LoadBalanced 負(fù)載均衡注解,會(huì)對(duì) RestTemplate 實(shí)例進(jìn)行封裝,創(chuàng)建動(dòng)態(tài)代理對(duì)象,并切入(AOP)負(fù)載均衡代碼,把請(qǐng)求分發(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 會(huì)向服務(wù)的多臺(tái)集群服務(wù)器分發(fā)請(qǐng)求
    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);
  }
}

第三步:訪問測(cè)試,ribbon 會(huì)把請(qǐng)求分發(fā)到 8001 和 8002 兩個(gè)服務(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)目用來測(cè)試遠(yuǎn)程調(diào)用和ribbon工具
# 等功能測(cè)試完成后,直接刪除
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ù)沒有提示,并且會(huì)有黃色警告
 # 重試次數(shù)越少越好,一般建議用0,1
 MaxAutoRetries: 1
 MaxAutoRetriesNextServer: 2

第三步:設(shè)置 RestTemplate 的請(qǐng)求工廠的超時(shí)屬性

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-對(duì)RestTemplate進(jìn)行增強(qiáng),封裝RestTemplate,添加負(fù)載均衡功能
 */
 @LoadBalanced
 @Bean public RestTemplate restTemplate(){
   //設(shè)置調(diào)用超時(shí)時(shí)間,超時(shí)后認(rèn)為調(diào)用失敗
 SimpleClientHttpRequestFactory f =
      new SimpleClientHttpRequestFactory();
   f.setConnectTimeout(1000);//建立連接等待時(shí)間
   f.setReadTimeout(1000);//連接建立后,發(fā)送請(qǐng)求后,等待接收響應(yīng)的時(shí)間
 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注入到這個(gè)變量
 //是為了后面做負(fù)載均衡測(cè)試,可以直接看到調(diào)用的是那個(gè)服務(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 完整接收請(qǐng)求協(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();
  }
}

第五步:測(cè)試 ribbon 重試機(jī)制

通過 ribbon 訪問 item-service,當(dāng)超時(shí),ribbon 會(huì)重試請(qǐng)求集群中其他服務(wù)器

http://localhost:3001/item-service/35

到此這篇關(guān)于深入學(xué)習(xí)Spring Cloud-Ribbon的文章就介紹到這了,更多相關(guān)Spring Cloud-Ribbon內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論