Spring Boot2.5.3集成Hystrix实现服务熔断

1. 添加必要依赖

<!-- Hystrix -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>

2. 修改配置文件

在application.yml中开启熔断器

spring:
  cloud:
  	#开启hystrix熔断器
    circuitbreaker:
      hystrix:
        enabled: true

3. 在消费者服务的启动类添加注解

// @EnableHystrix 包含 @EnableCircuitBreaker
@EnableHystrix
@EnableFeignClients
@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

4. 在源码中使用

基于Fegin的服务调用

@RestController
public class HelloController {

    @Autowired
    private HelloFeignService helloFeignService ;
    
    @GetMapping("/hello") 
    @HystrixCommand(fallbackMethod = "helloError")
    public String call() {
        // 像调用本地服务一样
        return helloFeignService.hello();
    }
	
	 //熔断回调方法,名称一定要和fallbackMethod中的一样
    public String helloError(){
        return "终于熔断了...";
    } 
}

补充:HelloFeignService 接口

//表示我们需要调用已在服务注册中心注册过的服务是my-producer
@FeignClient(name = "my-producer" )
public interface HelloFeignService {
	
	@GetMapping("/hello")
    public String hello();  
    // 添加跟调用目标一样的方法声明,二者保持一致即可,不需要实现
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值