SpringCloud-使用熔斷器防止服務雪崩-Ribbon和Feign方式(附代碼下載)

来源:https://www.cnblogs.com/badaoliumangqizhi/archive/2019/10/17/11695824.html
-Advertisement-
Play Games

場景 SpringCloud-服務註冊與實現-Eureka創建服務註冊中心(附源碼下載): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102535957 SpringCloud-服務註冊與實現-Eureka創建服務提供者(附源 ...


場景

SpringCloud-服務註冊與實現-Eureka創建服務註冊中心(附源碼下載):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102535957

SpringCloud-服務註冊與實現-Eureka創建服務提供者(附源碼下載):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102558004

SpringCloud-創建服務消費者-Ribbon方式(附代碼下載):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102558080

SpringCloud-創建服務消費者-Feign方式(附代碼下載)::

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102595895

在上面已經實現服務註冊中心、服務提供者和以Ribbon方式和Fign方式實現服務消費者的前提下,使用熔斷器防止服務雪崩。

在微服務架構中,根據業務來拆分成一個個的服務,服務與服務之間可以通過 RPC 相互調用,在 Spring Cloud 中可以用 RestTemplate + Ribbon 和 Feign 來調用。為了保證其高可用,單個服務通常會集群部署。由於網路原因或者自身的原因,服務並不能保證 100% 可用,如果單個服務出現問題,調用這個服務就會出現線程阻塞,此時若有大量的請求涌入,Servlet 容器的線程資源會被消耗完畢,導致服務癱瘓。服務與服務之間的依賴性,故障會傳播,會對整個微服務系統造成災難性的嚴重後果,這就是服務故障的 “雪崩” 效應。

熔斷器打開後,為了避免連鎖故障,通過 fallback 方法可以直接返回一個固定值。

註:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關註公眾號
霸道的程式猿
獲取編程相關電子書、教程推送與免費下載。

實現

Ribbon中使用熔斷器

SpringCloud-創建服務消費者-Ribbon方式(附代碼下載):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102558080

在上面使用Ribbon實現創建服務消費者。

我們在pom.xml中加入hystrix的依賴:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

 

完整pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.badao</groupId>
        <artifactId>hello-spring-cloud-dependencies</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../hello-spring-cloud-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>hello-spring-cloud-web-admin-ribbon</artifactId>
    <packaging>jar</packaging>

    <name>hello-spring-cloud-web-admin-ribbon</name>
    <url>https://blog.csdn.net/badao_liumang_qizhi</url>
    <inceptionYear>2019-Now</inceptionYear>

    <dependencies>
        <!-- Spring Boot Begin -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot End -->

        <!-- Spring Cloud Begin -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!-- Spring Cloud End -->

        <!-- 解決 thymeleaf 模板引擎一定要執行嚴格的 html5 格式校驗問題 -->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.funtl.hello.spring.cloud.web.admin.ribbon.WebAdminRibbonApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

 

然後在應用啟動類Application中增加@EnableHystrix註解

package com.badao.hello.spring.cloud.web.admin.ribbon;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class WebAdminRibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebAdminRibbonApplication.class, args);
    }
}

 

然後在Service中添加@HystrixCommand註解

在 Ribbon 調用方法上增加 @HystrixCommand 註解並指定 fallbackMethod 熔斷方法。

package com.badao.hello.spring.cloud.web.admin.ribbon.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class AdminService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String sayHi(String message) {
        return restTemplate.getForObject("http://hello-spring-cloud-service-admin/hi?message=" + message, String.class);
    }

    public String hiError(String message) {
        return "Hi,your message is :\"" + message + "\" but request error.";
    }
}

 

 

測試熔斷器

為了測試熔斷器效果,我們將服務提供者關閉,此時再次請求:

 

 http://localhost:8764/hi?message=HelloRibbon

Feign中使用熔斷器

Feign自帶熔斷器,所以不用添加依賴,只需要在配置文件中配置打開。

feign:
  hystrix:
    enabled: true

完整配置文件:

spring:
  application:
    name: hello-spring-cloud-web-admin-feign
  thymeleaf:
    cache: false
    mode: LEGACYHTML5
    encoding: UTF-8
    servlet:
      content-type: text/html

server:
  port: 8765

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

feign:
  hystrix:
    enabled: true

 

然後再Service中增加fallback指定類

package com.badao.hello.spring.cloud.web.feign.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "hello-spring-cloud-service-admin", fallback = AdminServiceHystrix.class)
public interface AdminService {

    @RequestMapping(value = "hi", method = RequestMethod.GET)
    public String sayHi(@RequestParam(value = "message") String message);
}

 

此時再service包下創建熔斷器並實現對應的Feign介面

package com.badao.hello.spring.cloud.web.feign.service;

import org.springframework.stereotype.Component;

@Component
public class AdminServiceHystrix implements AdminService {

    @Override
    public String sayHi(String message) {
        return "Hi,your message is :\"" + message + "\" but request error.";
    }
}

 

然後將服務提供者關閉,再次請求:

http://localhost:8765/hi?message=HelloFeign

代碼下載

https://download.csdn.net/download/badao_liumang_qizhi/11871136


 


  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 問題:js通過方法返回一個字面量對象和返回一個提前已經定義好的字面量對象有區別嗎? 答案:有 我們先來看看第一種情況,fun1方法返回一個提前沒定義的字面量對象,然後通過調用方法返回三個對象,分別是obj1, obj2, obj3,然後我修改obj2對象的age方法,列印obj1, obj2, ob ...
  • 在pc 管理系統這種類型的產品,通常會涉及到賬號許可權的控制,不同的賬號許可權能瀏覽的功能模塊是不同的,對應側邊欄菜單模塊的顯示也會不同。 ...
  • 方案一:在data中給input的值賦一個初始值 方案二:在給input賦值時,使用this.$set ...
  • Tinypng: 地址:https://tinypng.com/ 這款工具最大限度的做到對畫質無損的進行壓縮。 這個工具同時支持對Jpg和Png的壓縮。 Tinypng也支持Wordpress和magento的使用。 > 本文來自[木莊網路博客]> 強烈推薦一款圖片無損壓縮工具 ...
  • 描述在本地測試代碼沒問題,但是部署到伺服器上時就報錯。錯誤> cross-env WEBPACK_TARGET=node NODE_ENV=production node ./server/app.jstruethe server is start at port 3333/usr/share/ng... ...
  • 一、mock 1、簡介 mock是一個模擬數據生成器,旨在幫助前端獨立於後端進行開發,幫助編寫單元測試。其可模擬 Ajax 並返回模擬數據,使前端不用去調用後端的介面,方便測試。 2、vue直接使用mock step1:安裝mock step2:直接引入mock.js,並編寫mock介面(Mock. ...
  • 當頁面引入百度地圖時,谷歌瀏覽器的控制台會彈出一個警告信息,錯誤提示如下圖所示: 解決方案如下: 把api引用url裡面的 api 改為 getscript 將代碼: 修改為: 完... ...
  • Ajax設置自定義請求頭的兩種方法 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...