前言:
因为最近做一个请求你其他项目接口的功能,为防止请求超时,所以就想到了SpringCloud组件的Hystrix做熔断处理,这个组件的讲解可以看https://blog.youkuaiyun.com/loushuiyifan/article/details/82702522这位博主的详细讲解,主要就是做一个熔断操作,防止前端用户一直等待请求回馈。
实现:
- 添加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>
-
配置yml
hystrix: command: default: execution: isolation: strategy: THREAD thread: # 线程超时10秒,调用Fallback方法 timeoutInMilliseconds: 10000
-
创建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; } }
-
添加@HystrixCommand注解 需要注意业务传参和下面的fallback的参数数量一致,否则会报错
@Override @HystrixCommand(fallbackMethod = "fallback") public ResultEntity bankServiceConfirm() { return ResultEntity.error("确认流程异常"); } } public ResultEntity fallback() { return ResultEntity.error("请求超时......."); }
-
演示
打了断点
请求超时后执行 fallback代码