当前位置: 首页 > news >正文

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

一 服务降级的说明

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.lryc.cn/news/126925.html

相关文章:

  • 第 3 章 稀疏数组和队列(1)
  • 7-10 奇偶分家
  • 使用词向量以数学方式查找具有相似含义的单词
  • opencv实现以图搜图
  • 爬虫工作中代理失效了怎么处理?
  • 使用虚拟环境conda安装不同版本的cuda,cudnn,pytorch
  • 【24择校指南】华东师范大学计算机考研考情分析
  • 什么是LAXCUS分布式操作系统?
  • Redis数据结构——链表list
  • [自学记录06|*百人计划]Gamma矫正与线性工作流
  • 【数据结构】二叉树链式结构的实现及其常见操作
  • 从零实战SLAM-第九课(后端优化)
  • Python Opencv实践 - 图像金字塔
  • Baumer工业相机堡盟工业相机如何通过BGAPI SDK设置相机的固定帧率(C++)
  • 计算机竞赛 python+大数据校园卡数据分析
  • DNNGP模型解读-early stopping 和 batch normalization的使用
  • 【目标检测】目标检测 相关学习笔记
  • 面试攻略,Java 基础面试 100 问(十六)
  • 章节5:脚本注入网页-XSS
  • ATF(TF-A)安全通告 TFV-5 (CVE-2017-15031)
  • 迅捷视频工具箱:多功能音视频处理软件
  • linux--fork()详解
  • go_并发编程(1)
  • 第一百一十五回 权限管理包permission_handler
  • 【机器学习】sklearn数据集的使用,数据集的获取和划分
  • Mysql之 optimizer_trace 相关总结
  • 【Linux命令详解 | wget命令】 wget命令用于从网络下载文件,支持HTTP、HTTPS和FTP协议
  • DockePod信号处理机制与僵尸进程优化
  • NetApp StorageGRID 对象存储,使您能够跨公有、私有云和混合多云环境管理非结构化数据
  • 使用Java服务器实现UDP消息的发送和接收(多线程)