springcloud3 hystrix實現服務降級的案例配置2

一 服務降級的說明

1.1 服務降級說明

"服務器忙,請稍后在試"不讓客戶達等待,立即返回一個友好的提示。

1.2 服務降級的觸發情況

1.程序運行異常;

2.超時;

3.服務熔斷觸發服務降級;4

.線程池/信號量打滿也會導致服務降級

1.3 通用注解

1.4? hystrix的作用

在springcloud的框架里,熔斷機制是通過hystrix實現,hystrix會監控服務之間的調用。當失敗調用達到一定的閾值,默認是5s內失敗20次,就會啟用hystrix的熔斷機制,使用命令@HystrixCommand。

二 案例:對每一個方法實行降級處理

2.1 消費端

2.1.1 pom文件

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

2.1.2 設置降級規則

代碼

 @GetMapping(value = "/consumer/payment/nacos/{id}")@HystrixCommand(fallbackMethod = "dealFallBackInfo",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")})public String paymentInfo(@PathVariable("id") Long id){System.out.println("獲取服務器配置信息serverUrl:"+serverURL);System.out.println("9008的controller獲取id:"+id);String str=orderConsumerService.getPaymentByIdLjf22222(id);return "ok:"+serverURL+""+str;}@GetMapping(value = "/consumer/getinfo/{id}")public Object getUserInfo(@PathVariable("id") Long id){User u=new User(id.intValue(),"beijing"+id);return  orderConsumerService.postQueryParams(u);}public String dealFallBackInfo(@PathVariable("id") Long id){return "我是消費者9008,服務出錯了,進行服務降級"+id;}

?2.1.3 開啟hystrix熔斷

添加:@EnableHystrix 注解

?2.2?服務端

2.2.1 pom文件

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

2.2.2?設置降級規則

1.代碼

    @GetMapping(value = "/ljf/getinfo/{id}")@HystrixCommand(fallbackMethod = "dealFallBackInfo",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="3000")})public String getPayment(@PathVariable("id") Integer id){try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}int k=10/0;System.out.println("================服務9009 獲取到的參數id:"+id);return "服務9009 獲取到的參數id:"+id;}@PostMapping("/path")public  String postQueryParams(@RequestBody User user) throws JsonProcessingException {String str=  new JsonMapper().writeValueAsString(user);System.out.println("post提交....");return str;}public String dealFallBackInfo(@PathVariable("id") Long id){return "我是消費者9009,服務出錯了,進行服務降級"+id;}

2.截圖

?2.2.3 開啟hystrix熔斷

??2.3?啟動服務測試

1.啟動nacos,啟動sleuth

2.啟動consumer9008? ?provider9009

?3.測試

三 案例:設置全局降級處理辦法

3.1 消費端設置

1.代碼

package com.ljf.mscloud.controller;import com.ljf.mscloud.model.User;
import com.ljf.mscloud.service.OrderConsumerService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;/*** @ClassName: OrderConsumerController* @Description: TODO* @Author: admin* @Date: 2023/08/14?18:09:14?* @Version: V1.0**/
@RestController
@Slf4j
@RefreshScope //支持Nacos的動態刷新功能。
//@DefaultProperties(defaultFallback = "globalFallBackInfo")
public class OrderConsumerController {@Value("${service-url.nacos-user-service}")private String serverURL;@Autowiredprivate OrderConsumerService orderConsumerService;@GetMapping(value = "/consumer/payment/nacos/{id}")@HystrixCommand(fallbackMethod = "dealFallBackInfo",commandProperties = {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")})public String paymentInfo(@PathVariable("id") Long id){System.out.println("獲取服務器配置信息serverUrl:"+serverURL);System.out.println("9008的controller獲取id:"+id);String str=orderConsumerService.getPaymentByIdLjf22222(id);return "ok:"+serverURL+""+str;}@GetMapping(value = "/consumer/getinfo/{id}")public Object getUserInfo(@PathVariable("id") Long id){User u=new User(id.intValue(),"beijing"+id);return  orderConsumerService.postQueryParams(u);}public String dealFallBackInfo(@PathVariable("id") Long id){return "我是消費者9008,服務出錯了,進行服務降級"+id;}public String globalFallBackInfo(){return "Global異常處理信息,請稍后再試,客戶端9008";}
}

2.截圖

?原因在沒有在制定方法加:@HystrixCommand? 那么加上此注解后:

?再次訪問:http://localhost:9008/consumer/getinfo/666

四 案例:給Feginclient注解的接口上添加降級規則

4.1 controller

package com.ljf.mscloud.controller;import com.ljf.mscloud.model.User;
import com.ljf.mscloud.service.OrderConsumerService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;/*** @ClassName: OrderConsumerController* @Description: TODO* @Author: admin* @Date: 2023/08/14?18:09:14?* @Version: V1.0**/
@RestController
@Slf4j
@RefreshScope //支持Nacos的動態刷新功能。
//
//@DefaultProperties(defaultFallback = "globalFallBackInfo")
public class OrderConsumerController {@Value("${service-url.nacos-user-service}")private String serverURL;@Autowiredprivate OrderConsumerService orderConsumerService;@GetMapping(value = "/consumer/payment/nacos/{id}")//   @HystrixCommand(fallbackMethod = "dealFallBackInfo",commandProperties = {//        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")// })public String paymentInfo(@PathVariable("id") Long id){System.out.println("獲取服務器配置信息serverUrl:"+serverURL);System.out.println("9008的controller獲取id:"+id);String str=orderConsumerService.getPaymentByIdLjf22222(id);return "ok:"+serverURL+""+str;}@GetMapping(value = "/consumer/getinfo/{id}")// @HystrixCommandpublic Object getUserInfo(@PathVariable("id") Long id){User u=new User(id.intValue(),"beijing"+id);//  int age = 10/0;return  orderConsumerService.postQueryParams(u);}public String dealFallBackInfo(@PathVariable("id") Long id){return "我是消費者9008,服務出錯了,進行服務降級"+id;}public String globalFallBackInfo(){return "Global異常處理信息,請稍后再試,客戶端9008";}
}

4.2 service

package com.ljf.mscloud.service;import com.ljf.mscloud.model.User;
import feign.Headers;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
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;@Component
@FeignClient(value = "mscloud-fegin-nacos-hystrix-provider9009",fallback = PaymentFallbackService.class)
public interface OrderConsumerService {@GetMapping(value = "/ljf/getinfo/{yyid}") //相當于:public String getPaymentByIdLjf22222(@PathVariable("yyid") Long ssid);// @Headers({"Content-Type: application/json"})// @PostMapping("/path")@PostMapping(value = "/path",consumes ="application/json")String postQueryParams(@RequestBody User user);
}

4.3 fallback實現類

@Component
public class PaymentFallbackService  implements OrderConsumerService{@Overridepublic String getPaymentByIdLjf22222(Long ssid) {return "getPaymentByIdLjf22222方法出現問題開始降級";}@Overridepublic String postQueryParams(User user) {return "postQueryParams方法出現問題開始降級";}
}

?4.4 配置文件

?4.5 測試

1.故意只啟動 consuemr9008,不啟動provider9009 模擬宕機的情況

2.測試

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/40779.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/40779.shtml
英文地址,請注明出處:http://en.pswp.cn/news/40779.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

電商增強現實3D模型優化需要關注的4個方面

到目前為止&#xff0c;AR技術已經發展到足以在更廣泛的范圍內實施。 在電子商務中&#xff0c;這項技術有望提供更令人興奮的購物體驗。 為了實現這一目標&#xff0c;在這篇博客中&#xff0c;我將介紹如何針對電子商務中的 AR 優化 3D 模型。 推薦&#xff1a;用 NSDT編輯器…

Python 函數

Built-in Functions — Python 3.11.4 documentation

Transformer(二)(VIT,TNT)(基于視覺CV)

目錄 1.視覺中的Attention 2.VIT框架&#xff08;圖像分類&#xff0c;不需要decoder&#xff09; 2.1整體框架 2.2.CNN和Transformer遇到的問題 2.3.1CNN 2.3.2Transformer 2.3.3二者對比 2.4.公式理解 3TNT 參考文獻 1.視覺中的Attention 對于人類而言看到一幅圖可以立…

區塊鏈系統探索之路:私鑰的壓縮和WIF格式詳解

在前面章節中&#xff0c;我們詳細介紹了公鑰的壓縮&#xff0c;在比特幣網絡中&#xff0c;一個私鑰可以對應兩個地址&#xff0c;一個地址是由未壓縮公鑰所生成的地址&#xff0c;另一個就是由壓縮公鑰所創建的地址&#xff0c;從公鑰到區塊鏈地址的轉換算法&#xff0c;我們…

【設計模式——學習筆記】23種設計模式——解釋器模式Interpreter(原理講解+應用場景介紹+案例介紹+Java代碼實現)

案例引入 通過解釋器模式來實現四則運算&#xff0c;如計算ab-c的值&#xff0c;具體要求 先輸入表達式的形式&#xff0c;比如abc-de&#xff0c;要求表達式的字母不能重復在分別輸入a,b,c,d,e的值最后求出結果 傳統方案 編寫一個方法&#xff0c;接收表達式的形式&#xf…

基于Pan-Tompkins的實時QRS檢測算法:便攜式ANSI-C實現深入解析

引言 隨著醫學工程和移動設備技術的進步&#xff0c;實時QRS檢測算法在心電圖分析中變得越來越重要。其中&#xff0c;Pan-Tompkins算法由于其高效性和準確度&#xff0c;在許多應用中都受到廣泛認可。本文將深入探討此算法的ANSI-C實現&#xff0c;并提供詳細的代碼實例。 1…

【kubernetes】配置資源管理

目錄 Secret 創建 Secret 1、用kubectl create secret命令創建Secret 2、內容用 base64 編碼&#xff0c;創建Secret 使用方式 1、將 Secret 掛載到 Volume 中&#xff0c;以 Volume 的形式掛載到 Pod 的某個目錄下 2、將 Secret 導出到環境變量中 ConfigMap 創建 Co…

請解釋一下CSS中的rem和em單位有什么不同,分別如何使用?

聚沙成塔每天進步一點點 ? 專欄簡介? CSS中的rem和em單位的區別和使用? em單位使用示例&#xff1a; ? rem 單位使用示例&#xff1a; ? 區別和適用場景? 寫在最后 ? 專欄簡介 前端入門之旅&#xff1a;探索Web開發的奇妙世界 記得點擊上方或者右側鏈接訂閱本專欄哦 幾何…

Nginx常見的三個漏洞

目錄 $uri導致的CRLF注入漏洞 兩種常見場景 表示uri的三個變量 案例 目錄穿越漏洞 案例 Http Header被覆蓋的問題 案例 $uri導致的CRLF注入漏洞 兩種常見場景 用戶訪問http://example.com/aabbcc&#xff0c;自動跳轉到https://example.com/aabbcc 用戶訪問http://exa…

[英語單詞] compat; compatibility;compact;entry_SYSENTER_compat

簡介 這個詞compat&#xff0c;馬上就會被簡寫形式所替代。所以一定不要和compact混淆。第一次看到還以為是個新詞來&#xff0c;后來發現是一個縮寫形式。就是兼容的意思&#xff0c;就如同兼容以往的就有事物。 syscall: 32bit: 兼容 entry_SYSENTER_compat 這個是32位程序…

MySQL存儲過程 、存儲函數、以及優缺點

存儲過程 VS 存儲函數&#xff08;函數&#xff09; | | 關鍵字 |調用語法 | 返回值 | 應用場景 | |-存儲過程-|-procedure-|-call 存儲過程()-|-理解為0個或多個-|-一般用于更新-| | 存儲函數 | function | select 函數() | 只能是一個 | 一般用于查詢結構為一個值并返回時| …

三、python Django ORM postgresql[數據定時備份、數據恢復]

一、數據定時備份 解釋&#xff1a;備份指定數據庫&#xff0c;能有效在發生錯誤時&#xff0c;預防錯誤&#xff0c;進行恢復 1.基本備份 #!/bin/bash sudo -u postgres pg_dump -U postgres -d dbname -Fc > /home/postgres/backup/backup.dump # sudo -u postgres&…

訊飛星火、文心一言和通義千問同時編“貪吃蛇”游戲,誰會勝出?

同時向訊飛星火、文心一言和通義千問三個國產AI模型提個相同的問題&#xff1a; “python 寫一個貪吃蛇的游戲代碼” 看哪一家AI寫的程序直接能用&#xff0c;誰就勝出&#xff01; 訊飛星火 訊飛星火給出的代碼&#xff1a; import pygame import sys import random# 初…

Android 13 開啟關閉飛行模式

一.背景 由于客戶定制的Settings里面需要開啟和關閉飛行模式,所以需要實現此功能。 二.前提條件 首先應用肯定要是系統應用,并且導入framework.jar包,具體可以參考: Android 應用自動開啟輔助(無障礙)功能并使用輔助(無障礙)功能_android 自動開啟無障礙服務_龔禮鵬的博客…

步入React正殿 - React組件設計模式

目錄 擴展學習資料 高階組件 /src/components/hoc/withTooltip.js /src/components/hoc/itemA.jsx /src/components/hoc/itemB.jsx /src/App.js 函數作為子組件【Render pprops】 函數作為子組件 /src/components/rp/itemC.jsx【父組件】 /src/components/rp/withToo…

C#調用C++ DLL傳參byte[]數組字節值大于127時會變為0x3f的問題解決

最近做了一個網絡編程的DLL給C#調用&#xff0c;DLL中封裝了一個TCP Client的函數接口&#xff0c;如下所示 //C TCP報文發送接口 int TcpClient_send(unsigned char* buffSend, unsigned int nLen) {unsigned char buff[1024];int len StringToHex(buffSend, buff);int nRet…

stable diffusion安裝包和超火使用文檔,數字人制作網址

一&#xff1a;文生圖、圖生圖 1&#xff1a;stable diffusion&#xff1a;對喜歡二次元、美女小姐姐、大眼萌妹的人及其友好哈哈(o^^o) 1&#xff09;&#xff1a;秋葉大神安裝包和模型包&#xff1a; 鏈接&#xff1a;https://pan.baidu.com/s/11_kguofh76gwhTBPUipepw 提…

機器學習 | Python實現GBDT梯度提升樹模型設計

機器學習 | Python實現GBDT梯度提升樹模型設計 目錄 機器學習 | Python實現GBDT梯度提升樹模型設計基本介紹模型描述模型使用參考資料基本介紹 機器學習 | Python實現GBDT梯度提升樹模型設計。梯度提升樹(Grandient Boosting)是提升樹(Boosting Tree)的一種改進算法,GBDT也…

Java System.arraycopy() 對比 C++ memcpy()

System.arraycopy() java.lang.System類為標準輸入和輸出、加載文件和庫或訪問外部定義的屬性提供了有用的方法。 java.lang.System.arraycopy&#xff08;&#xff09;方法將源數組從特定的起始位置復制到上述位置的目標數組。要復制的參數的數量由一個參數決定。 source_Pos…

前端文件下載通用方法

zip文件和xlsx文件 import axios from axios import { getToken } from /utils/authconst mimeMap {xlsx: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,zip: application/zip }const baseUrl process.env.VUE_APP_BASE_API // zip下載 export functi…