JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

SpringBoot熔断的简单理解

wys521 2024-11-17 16:57:41 精选教程 15 ℃ 0 评论

熔断有点像java遇到异常时定位到指定错误页面,但是熔断与异常处理的本质区别是熔断可以防止服务因为接口的并发响应超时导致系统的雪崩,

个人的理解就是熔断不会让请求因为某个服务接口死等影响整个系统,

熔断功能:

1 包含了异常处理、

2 同时包含了超时处理

如:调用链路 A--->B----->C

若b到c出现故障,如果不做任何处理,会导致越来越多的请求等待,最终可能导致B或C的崩溃

有了熔断,若B-->C只能每分钟处理极限为10000个请求,当超过10000个时,超出之外的大部分会被熔断处理,这样当有20000个请求时,由于超过10000之外的请求大部分熔断了,

这样可以保障C的正常运行

package com.example.demo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * Created by andy.
 */
//@RestController注解相当于@ResponseBody+@Controller合在一起的作用。
@RestController
public class HysTestController {
 
   /* @HystrixCommand(fallbackMethod="helloFallbackMethod",commandProperties =
     {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds" , value = "10000")})*/
   @HystrixCommand(fallbackMethod="helloFallback")
    @GetMapping("/hello")
    public String hello(@RequestParam(name = "num") int num) throws InterruptedException {
        Thread.sleep(10000);//模拟超时
        int a = 100 / num;//除以0时会出错,也会熔断
        return "ok";
    }
	
	//tt响应超时,直接跳转到这里处理
    private String helloFallback(@RequestParam(name = "num") int num){
        return "fall back";
    }
}

具体实现方法:
在启动类添加注解@EnableHystrix表示加入熔断机制

在Controller层的具体的方法路由上添加@HystrixCommand(fallbackMethod="helloFallback")表示该方法在出错或者是超时时会跳转到helloFallback。
例如在代码中如果num=0,这时就会抛异常,熔断就会跳转到helloFallbackMethod;springboot的默认的超时时间是1000ms,
代码中sleep(5000)也会导致熔断并跳转到helloFallbackMethod;默认多少时间算超时可以通过在application.yml文件中进行配置,
如下hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=30000;
这里添加到application.yml中就可以了,表示30000ms超时。

熔断跳转方法:helloFallback,helloFallback的参数必须与路由方法的参数一致

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表