springcloud-hystrix熔断实践

32 篇文章 0 订阅
10 篇文章 0 订阅

1、简单介绍

Hystrix是一个延迟和容错库,旨在隔离对远程系统,服务和第三方库的访问点,停止级联故障,并在不可避免发生故障的复杂分布式系统中实现弹性。

2、springboot集成hystrix熔断实践

1. 导入依赖

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

2. 编写熔断的方法

首先这是位于服务提供者的代码。当hello方法抛出异常时,它通过 @HystrixCommand(fallbackMethod = “Hystrix”)这个注解,去调用Hystrix方法

    @RequestMapping("/findById")
    @HystrixCommand(fallbackMethod = "Hystrix")
    public User hello(Long id){
        User user = userService.findById(id);
        if (user==null){
            throw new RuntimeException("id => " + id + ",不存在该用户,或者信息无法找到");
        }
        return user;
    }

    //备选方法
    public User Hystrix(Long id){
        return new User()
                .setId(id)
                .setName("id => " + id + ",不存在该用户,或者信息无法找到")
                .setDb("no db ");
    }

3. 在启动类中启动项目对熔断器的支持

@EnableCircuitBreaker 表示添加对熔断的支持

package com.hzxy.springcloud;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@MapperScan("com.hzxy.springcloud.mapper")
@EnableDiscoveryClient       //服务发现
@EnableEurekaClient      //在服务启动后自动注册到Eureka中
@SpringBootApplication
@EnableCircuitBreaker     //添加对熔断的支持
public class HystrixProvider_8001 {
    public static void main(String[] args) {
        SpringApplication.run(HystrixProvider_8001.class,args);
    }
}

3、测试

访问数据库含有的数据,它找出结果
在这里插入图片描述

访问数据库没有的数据,它会执行备用方法,如下
在这里插入图片描述
测试成功!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值