springcloud-hystrix熔断实践

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、测试

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

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

猜你喜欢

转载自blog.csdn.net/weixin_43520670/article/details/114333758