springcloud熔断使用

说明:这里只说明熔断使用,不对作用进行解释介绍

准备:需要A服务 B服务都注册到注册中心,A服务需要调用B服务,那么熔断就是在B服务中。我这边A服务调用B服务是用的openfeign。

A服务内容【一些注册中心配置就不整了】:

pom文件:我这里面跟熔断相关的配置没有

yml文件:我这里面跟熔断相关的配置没有

控制层:ATestController

@Autowired
private ATestService atestService;

@GetMapping("forHystrix")
public String forHystrix(@RequestParam("a") int a){
    return atestService.forHystrix(a);
}

接口层:

@FeignClient(name = "B服务名称")
public interface ATestService {

    @GetMapping("forHystrix")
    String forHystrix(@RequestParam("a") int a);
}

接口实现层【这个是做降级的,要不要都行】:

@Service
public class ATestServiceImpl implements ATestService {

    public String forHystrix(int a){
        return "我是降级-forHystrix";
    }
}

B服务内容:

pom文件:

<!-- hystrix 熔断 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

yml文件:

hystrix:
  metrics:
    enabled: true

启动类:在启动类上加上 @EnableHystrix//开启熔断

控制层:BTestController

@Autowired 
private BTestService btestService;
@GetMapping("forHystrix")
public String forHystrix(@RequestParam("a") int a){
    a = btestService.forHystrix(a);
    return "hello forHystrix: a = "+ a;
}

接口层:

public interface BTestService {
    int forHystrix(int a);
}

接口实现类:

@Service
public class BTestServiceImpl implements BTestService {

    @HystrixCommand(fallbackMethod = "forHystrixError",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启路由
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")//请求失败率
    })//上面的配置意思是,开启路由,每请求10次该接口,有6次请求失败,那么Hystrix会开启服务熔断
    public int forHystrix(int a) {
        System.out.println(a);
        if(a == 1){
            int b = 1/0;
        }
        return a;
    }

    public int forHystrixError(int a){
        return -1;
    }
    
}

随便记录一下。。。。。。。。。。。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值