Hystrix熔断器

服务熔断

服务熔断:服务端,某个服务超时或者异常,引起熔断(保险丝)

服务提供者

导入依赖

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

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

编写配置文件

# spring配置
spring:
  application:
    name: springcloud-provider-dept #3个服务名称一致

# Eureka的配置,服务注册到哪里
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept-hystrix-8001 #修改Eureka上的默认描述信息!
    prefer-ip-address: true #true,可以显示服务的ip地址

开启相关功能

// 启动类
@SpringBootApplication
@EnableEurekaClient//在服务启动后自动注册到Eureka中!
@EnableDiscoveryClient//服务发现
// 添加对熔断的支持
@EnableCircuitBreaker
public class DeptProviderHystrix_8001 {

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

}

添加备选方案
@HystrixCommand(fallbackMethod = "hystrixGet"),指定备选方案(原方法发生异常时,触发备选方案)

// 提供Restful服务
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet")
    public Dept get(@PathVariable Long id) {
        Dept dept = deptService.queryById(id);

        if (dept == null) {
            throw new RuntimeException("id=>" + id + ",不存在该用户,或者信息无法找到!");
        }

        return dept;
    }

    // 备选方案
    public Dept hystrixGet(@PathVariable Long id) {
        return new Dept()
                .setDeptno(id)
                .setDname("id=>" + id + "没有对应的信息,null--@Hystrix")
                .setDb_source("no this database in MySQL");
    }

}

服务降级

服务降级:客户端,从整体的网站请求负载考虑,当某个服务熔断或者关闭之后,服务将不再被调用,此时在客户端,我们可以准备一个FallbackFactory,返回一个默认值(缺省值),整体的服务水平下降了,但是好歹能用,比直接挂掉强~

公共模块改造

导入依赖

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

指定降级策略,通过@FeignClient的fallbackFactory属性指定降级处理类

//@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT", fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService {

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);

}

降级处理类,实现FallbackFactory,在create方法中实现对应Feign接口,编写降级处理逻辑

// 降级
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory {

    @Override
    public DeptClientService create(Throwable throwable) {
        return new DeptClientService() {
            @Override
            public Dept queryById(Long id) {
                return new Dept()
                        .setDeptno(id)
                        .setDname("id=>" + id + "没有对应的信息,客户端提供了降级的信息,这个服务现在已经被关闭")
                        .setDb_source("没有数据~");
            }

            @Override
            public List<Dept> queryAll() {
                return null;
            }

            @Override
            public boolean addDept(Dept dept) {
                return false;
            }
        };
    }

}

服务消费者改造

导入依赖

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

编写配置文件

# 开启降级 feign.hystrix
feign:
  hystrix:
    enabled: true

此时再通过Feign调用接口,若失败则触发服务降级处理

Dashboard流监控

导入依赖

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

编写配置文件

server:
  port: 9001

开启相关功能

@SpringBootApplication
// 开启监控
@EnableHystrixDashboard
public class DeptConsumerDashboard_9001 {

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

}

服务提供方改造

增加依赖

        <!--actuator完善监控信息-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

开启相关功能,增加ServletRegistrationBean这个实例,在Dashboard的小猪页面填写当前服务的ip:port/actuator/hystrix.stream获取流数据

// 启动类
@SpringBootApplication
@EnableEurekaClient//在服务启动后自动注册到Eureka中!
@EnableDiscoveryClient//服务发现
// 添加对熔断的支持
@EnableCircuitBreaker
public class DeptProviderHystrix_8001 {

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

    // 增加一个 Servlet,配合监控使用
    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        registrationBean.addUrlMappings("/actuator/hystrix.stream");
        return registrationBean;
    }

}
posted @   不写代码想写诗的虫子  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示