Springboot整合Hystrix

前言:

因为最近做一个请求你其他项目接口的功能,为防止请求超时,所以就想到了SpringCloud组件的Hystrix做熔断处理,这个组件的讲解可以看https://blog.youkuaiyun.com/loushuiyifan/article/details/82702522这位博主的详细讲解,主要就是做一个熔断操作,防止前端用户一直等待请求回馈。

实现:

  1. 添加pom
            <!-- 监控熔断-->
            <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
                <version>2.1.1.RELEASE</version>
            </dependency>

     

  2. 配置yml

    hystrix:
      command:
        default:
          execution:
            isolation:
              strategy: THREAD
              thread:
                # 线程超时10秒,调用Fallback方法
                timeoutInMilliseconds: 10000

     

  3. 创建HystrixConfiguration

    package com.funi.psfs.bank.config;
    
    import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class HystrixConfiguration {
    
        @Bean
        public ServletRegistrationBean getServlet(){
            HystrixMetricsStreamServlet hystrixMetricsStreamServlet = new HystrixMetricsStreamServlet();
            ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(hystrixMetricsStreamServlet);
            servletRegistrationBean.setLoadOnStartup(1);
            servletRegistrationBean.addUrlMappings("/hystrix.stream");
            servletRegistrationBean.setName("HystrixMetricsStreamServlet");
            return servletRegistrationBean;
        }
    }
    

     

  4. 添加@HystrixCommand注解   需要注意业务传参和下面的fallback的参数数量一致,否则会报错

        @Override
        @HystrixCommand(fallbackMethod = "fallback")
        public ResultEntity bankServiceConfirm() {
                return ResultEntity.error("确认流程异常");
            }
        }
    
        public ResultEntity fallback() {
            return ResultEntity.error("请求超时.......");
        }

     

  5. 演示打了断点请求超时后执行 fallback代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值