springcloud3 hystrix实现服务降级的案例配置2

news/2025/3/1 17:07:23/

一 服务降级的说明

1.1 服务降级说明

"服务器忙,请稍后在试"不让客户达等待,立即返回一个友好的提示。

1.2 服务降级的触发情况

1.程序运行异常;

2.超时;

3.服务熔断触发服务降级;4

.线程池/信号量打满也会导致服务降级

1.3 通用注解

 

二 案例:对每一个方法实行降级处理

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.ppmy.cn/news/1037339.html

相关文章

Android源码修改点

Android 修改点 1、工厂版本去掉全屏弹框 修改文件 ImmersiveModeConfirmation.java 文件所处路径 frameworks/base/services/core/java/com/android/server/wm/ImmersiveModeConfirmation.java 修改 如下&#xff1a; private final class H extends Handler {private …

CentOS系统环境搭建(十四)——CentOS7.9安装elasticsearch-head

centos系统环境搭建专栏&#x1f517;点击跳转 关于node的安装请看上一篇CentOS系统环境搭建&#xff08;十三&#xff09;——CentOS7安装nvm&#xff0c;&#x1f517;点击跳转。 CentOS7.9安装elasticsearch-head 文章目录 CentOS7.9安装elasticsearch-head1.下载2.解压3.修…

深入解析 Axios Blob 的使用方法及技巧

在 Web 开发中&#xff0c;处理文件传输是一个常见的需求。Blob&#xff08;二进制对象&#xff09;是一种表示二进制数据的方式&#xff0c;常用于处理文件和多媒体数据。本文将介绍如何使用 Axios 和 Blob 来处理文件传输。 Axios Blob 概念 在开始之前&#xff0c;让我们先…

VSCode无法从Extensions下载工具时,把工具下载到本地并添加到VSCode编辑器

从VSCode 的 Extensions 下载 下载报错&#xff1a;Error while installing ...... extension. Please check the log for more details. 由于内网限制&#xff08;或者其他网络限制&#xff09;无法正常下载扩展工具到VSCode编辑器&#xff0c;可以把工具下载到本地再添加到V…

深入探索JavaEE单体架构、微服务架构与云原生架构

课程链接&#xff1a; 链接: https://pan.baidu.com/s/1xSI1ofwYXfqOchfwszCZnA?pwd4s99 提取码: 4s99 复制这段内容后打开百度网盘手机App&#xff0c;操作更方便哦 --来自百度网盘超级会员v4的分享 课程介绍&#xff1a; &#x1f50d;【00】模块零&#xff1a;开营直播&a…

CSRF

CSRF CSRF&#xff0c;跨站域请求伪造&#xff0c;通常攻击者会伪造一个场景&#xff08;例如一条链接&#xff09;&#xff0c;来诱使用户点击&#xff0c;用户一旦点击&#xff0c;黑客的攻击目的也就达到了&#xff0c;他可以盗用你的身份&#xff0c;以你的名义发送恶意请…

第六阶|见道明心的笔墨(上)从书法之美到生活之美——林曦老师的线上直播书法课

如果你有需要&#xff0c;可以找我的&#xff0c;我这边有老师的所有课程 如果你有需要&#xff0c;可以找我的&#xff0c;我这边有老师的所有课程

载入内存,让程序运行起来

如果你的电脑上安装了QQ&#xff0c;你希望和好友聊天&#xff0c;会双击QQ图标&#xff0c;打开QQ软件&#xff0c;输入账号和密码&#xff0c;然后登录就可以了。 那么&#xff0c;QQ是怎么运行起来的呢&#xff1f; 首先&#xff0c;有一点你要明确&#xff0c;你安装的QQ软…