Spring cloud微服务搭建(八)——Hystrix服务熔断

接上一篇:Spring cloud微服务搭建(七)——Feign面向接口编程

服务熔断,是指某个服务超时或异常,引起熔断,起到保险丝的作用。

针对服务方而言,只涉及修改服务提供方。

Maven依赖

<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    <version>2.2.7.RELEASE</version>
</dependency>

服务提供方

控制器
  • @HystrixCommand:用来修饰要熔断的服务方法

    • fallbackMethod:String类型属性,用于指定有异常抛出时,回调方法名
  • 新增回调方法

    此处为hystrixFallback()

    • 回调方法hystrixFallback()&被@HystrixCommand注解的方法queryById()
      • 返回类型保持一致
      • 参数列表保持一致
@RestController
public class DepartmentController {
    @Autowired
    private DeparmentService deparmentService;

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixFallback")
    public Department queryById(@PathVariable("id") int id){
        Department department=deparmentService.queryById(id);
        if(null==department){
            throw new RuntimeException("id--> "+ id);
        }
        return department;
        
    }

    public Department hystrixFallback(@PathVariable("id") int id){
        return new Department().setDeptNo(id)
                .setDeptName("id-->"+id+" not exists!");
    }
   
}
启动类

新增@EnableHystrix注解修饰启动类。开启Hystrix限流。

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableHystrix
public class DepartmentProvider8002 {
    public static void main(String[] args) {
        SpringApplication.run(DepartmentProvider8002.class,args);

    }
}

测试执行

依次启动Eureka服务,服务提供方,基于Feign实现的客户端(消费方)服务。

首先输入http://localhost/consumer/dept/get/3 ,id为3,数据库存在记录,请求服务方的queryById()方法,正常返回。

在这里插入图片描述

在浏览器输入url地址:http://localhost/consumer/dept/get/30,id为30,在数据库中并不存在记录,此时queryById()方法抛出异常,回调备用方法hystrixFallback(),显示内容如下。

在这里插入图片描述

服务发生异常时,调用了备用方法,实现了服务熔断。

更多:
Spring cloud开发环境搭建(一)——maven依赖

Spring cloud微服务搭建(二)——pojo实体类

Spring cloud微服务搭建(三)—— Spring cloud服务提供方

Spring cloud微服务搭建(四)——Spring cloud 消费方

Spring cloud微服务搭建(五)——Eureka注册服务

Spring cloud微服务搭建(六)——Ribbon负载均衡

Spring cloud微服务搭建(七)——Feign面向接口编程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值