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

news2024/7/4 4:29: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;
    @Autowired
    private 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;
    @Autowired
    private 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}")
   // @HystrixCommand
    public 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{
    @Override
    public String getPaymentByIdLjf22222(Long ssid) {
        return "getPaymentByIdLjf22222方法出现问题开始降级";
    }

    @Override
    public String postQueryParams(User user) {
        return "postQueryParams方法出现问题开始降级";
    }
}

 4.4 配置文件

 4.5 测试

1.故意只启动 consuemr9008,不启动provider9009 模拟宕机的情况

2.测试

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/887873.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux命令200例:ps用于查看当前系统中运行的进程信息(常用)

&#x1f3c6;作者简介&#xff0c;黑夜开发者&#xff0c;全栈领域新星创作者✌。CSDN专家博主&#xff0c;阿里云社区专家博主&#xff0c;2023年6月csdn上海赛道top4。 &#x1f3c6;数年电商行业从业经验&#xff0c;历任核心研发工程师&#xff0c;项目技术负责人。 &…

【Python】Web学习笔记_flask(5)——会话cookie对象

HTTP是无状态协议&#xff0c;一次请求响应结束后&#xff0c;服务器不会留下对方信息&#xff0c;对于大部分web程序来说&#xff0c;是不方便的&#xff0c;所以有了cookie技术&#xff0c;通过在请求和响应保温中添加cookie数据来保存客户端的状态。 html代码&#xff1a; …

redis Windows版本安装过程(5.0.14)

官网不提供Windows版本的redis安装包&#xff0c;但可以在GitHub网站上找到redis的安装包&#xff1a; Releases tporadowski/redis GitHub &#xff08;相比较Linux其他版本的Redis,Windows版的redis的缺点是版本比较老&#xff0c;官方不提供且不更新&#xff09; 1、zip…

界面组件Telerik UI for WinForms R2 2023——拥有VS2022暗黑主题

Telerik UI for WinForms拥有适用Windows Forms的110多个令人惊叹的UI控件。所有的UI for WinForms控件都具有完整的主题支持&#xff0c;可以轻松地帮助开发人员在桌面和平板电脑应用程序提供一致美观的下一代用户体验。 Telerik UI for WinForms R2 2023于今年6月份发布&…

Vue2到3 Day6 全套学习内容,众多案例上手(内付源码)

简介&#xff1a; Vue2到3 Day1-3 全套学习内容&#xff0c;众多案例上手&#xff08;内付源码&#xff09;_星辰大海1412的博客-CSDN博客本文是一篇入门级的Vue.js介绍文章&#xff0c;旨在帮助读者了解Vue.js框架的基本概念和核心功能。Vue.js是一款流行的JavaScript前端框架…

[C++]笔记 - 知识点积累

一.运算符的优先级 一共15个级别 最高优先级 : () []最低优先级 :逗号表达式倒数第二低优先级 : 赋值和符合赋值(,,-...) ! >算术运算符 > 关系运算符 > && >> || >赋值运算符 二.数据类型转换 隐式类型转换 算数转换 char int long longlong flo…

【2023年11月第四版教材】《第5章-信息系统工程之软件工程(第二部分)》

《第5章-信息系统工程之软件工程&#xff08;第二部分&#xff09;》 1.3 软件设计1.4 软件实现&#xff3b;补充第三版教材内容&#xff3d; 1.5 部署交付 1.3 软件设计 1、结构化设计SD是一种面向数据流的方法&#xff0c;它以SRS和SA阶段所产生的DFD和数据字 典等文档为基础…

如何使用CSS实现一个渐变背景效果?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ 使用CSS实现渐变背景效果⭐ 线性渐变&#xff08;Linear Gradient&#xff09;⭐ 径向渐变&#xff08;Radial Gradient&#xff09;⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 记得点击上方或者右侧链接订…

genism word2vec方法

文章目录 概述使用示例模型的保存与使用训练参数详解&#xff08;[原链接](https://blog.csdn.net/weixin_44852067/article/details/130221655)&#xff09;语料库训练 概述 word2vec是按句子来处理的Sentences(句子们) 使用示例 from gensim.models import Word2Vec #sent…

ThreadLocal(超详细介绍!!)

关于ThreadLocal&#xff0c;可能很多同学在学习Java的并发编程部分时&#xff0c;都有所耳闻&#xff0c;但是如果要仔细问ThreadLocal是个啥&#xff0c;我们可能也说不清楚&#xff0c;所以这篇博客旨在帮助大家了解ThreadLocal到底是个啥&#xff1f; 1.ThreadLocal是什么&…

AgentBench::AI智能体发展的潜在问题一

从历史上看,几乎每一种新技术的广泛应用都会在带来新机遇的同时引发很多新问题,AI智能体也不例外。从目前的发展看,AI智能体的发展可能带来的新问题可能包括如下方面: 第一是它可能带来涉及个人数据、隐私,以及知识产权的法律纠纷的大幅增长。要产生一个优秀的AI智能体,除…

ZLMediakit编译(Win32)

ZLMediakit编译流程&#xff0c;本文是编译32位的ZLMediakit 下载OpenSSL 直接下载binary就好了&#xff0c;地址&#xff1a;https://slproweb.com/download/Win32OpenSSL-1_1_1u.msi 也可以根据自己的需求下载其他版本&#xff0c;地址https://slproweb.com/products/Win32…

[oneAPI] 手写数字识别-LSTM

[oneAPI] 手写数字识别-LSTM 手写数字识别参数与包加载数据模型训练过程结果 oneAPI 比赛&#xff1a;https://marketing.csdn.net/p/f3e44fbfe46c465f4d9d6c23e38e0517 Intel DevCloud for oneAPI&#xff1a;https://devcloud.intel.com/oneapi/get_started/aiAnalyticsToolk…

【C语言】自定义实现strcpy函数

大家好&#xff0c;我是苏貝&#xff0c;本篇博客带大家了解如何自定义实现strcpy函数&#xff0c;如果你觉得我写的还不错的话&#xff0c;可以给我一个赞&#x1f44d;吗&#xff0c;感谢❤️ 一. 了解strcpy函数。 函数原型&#xff1a;char* strcpy( char* destination , …

LLM - 大模型评估指标之 BLEU

目录 一.引言 二.BLEU 简介 1.Simple BLEU 2.Modified BLEU 3.Modified n-gram precision 4.Sentence brevity penalty 三.BLEU 计算 1.计算句子与单个 reference 2.计算句子与多个 reference 四.总结 一.引言 机器翻译的人工评价广泛而昂贵&#xff0c;且人工评估可…

【uni-app报错】获取用户收货地址uni.chooseAddress()报错问题

chooseAddress:fail the api need to be declared in …e requiredPrivateInf 原因&#xff1a; 小程序配置 / 全局配置 (qq.com) 解决&#xff1a; 登录小程序后台申请接口 按照流程申请即可 在项目根目录中找到 manifest.json 文件&#xff0c;在左侧导航栏选择源码视图&a…

代码pytorch-adda-master跑通记录

前言 最近在学习迁移学习&#xff0c;ADDA算法&#xff0c;由于嫌自己写麻烦&#xff0c;准备先跑通别人的代码。 代码名称&#xff1a;pytorch-adda-master 博客&#xff1a;https://www.cnblogs.com/BlairGrowing/p/17020378.html github地址&#xff1a;https://github.com…

Vue3 —— watchEffect 高级侦听器

该文章是在学习 小满vue3 课程的随堂记录示例均采用 <script setup>&#xff0c;且包含 typescript 的基础用法 前言 Vue3 中新增了一种特殊的监听器 watchEffect&#xff0c;它的类型是&#xff1a; function watchEffect(effect: (onCleanup: OnCleanup) > void,o…

第三届“赣政杯”网络安全大赛 | 赛宁筑牢安全应急防线

​​为持续强化江西省党政机关网络安全风险防范意识&#xff0c;提高信息化岗位从业人员基础技能&#xff0c;提升应对网络安全风险处置能力。由江西省委网信办、江西省发展改革委主办&#xff0c;江西省大数据中心、国家计算机网络与信息安全管理中心江西分中心承办&#xff0…

【负荷频率和电压控制】电力系统的组合负荷频率和电压控制模型研究(Simulink)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…