黑马十次方项目day08-01SpringCloud之Netflix Hystrix熔断器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33229669/article/details/87889998

一.为什么要使用熔断器

在微服务架构中通常会有多个服务层调用,基础服务的故障可能会导致级联故障,
进而造成整个系统不可用的情况,这种现象被称为服务雪崩效应。服务雪崩效应是一种
因“服务提供者”的不可用导致“服务消费者”的不可用,并将不可用逐渐放大的过程.

如果下图所示:A作为服务提供者,B为A的服务消费者,C和D是B的服务消费者。A
不可用引起了B的不可用,并将不可用像滚雪球一样放大到C和D时,雪崩效应就形成
了。

二. 什么是Hystrix

Hystrix [hɪst’rɪks]的中文含义是豪猪, 因其背上长满了刺,而拥有自我保护能力.
Hystrix 能使你的系统在出现依赖服务失效的时候,通过隔离系统所依赖的服务,防
止服务级联失败,同时提供失败回退机制,更优雅地应对失效,并使你的系统能更快地
从异常中恢复。
熔断器模式请看下图:

三. 快速体验Hystrix

要使用Hystrix, 必须依赖于Eureka 平台, 因此要先起 Eureka的服务.
接着启动tensquare_base 9001端口, tensquare_qa 9003端口.
使用day07所用到的Feign实现服务间的调用.
发送如下的get请求
http://localhost:9003/problem/label/1 ,响应的数据如下. 代表tensquare_qa服务成功调用了tensquare_base 服务的数据.

这时,如果把tensquare_base 服务停掉, 那么再次调用上面的接口, 则会返回执行出错.

而希望能够达到的目标是如果tensquare_base 服务出错, 希望能够去执行其他分支的代码执行业务性的操作.

1. 修改yml

修改tensquare_qa模块的application.yml ,开启hystrix.

feign:
  hystrix:
    enabled: true  # 开启熔断器

2.创建熔断实现类

在com.tensquare.qa.client包下创建impl包,包下创建熔断实现类,实现自接口
LabelClient

import com.tensquare.qa.client.BaseClient;
import entity.Result;
import entity.StatusCode;
import org.springframework.stereotype.Component;

@Component
public class BaseClientImpl implements BaseClient {
    @Override
    public Result findById(String labelId) {
        return new Result(false, StatusCode.ERROR,"熔断器触发了");
    }
}


3.修改LabelClient接口的注解

@ FeignClient(value="tensquare‐base",fallback = LabelClientImpl.class)
完整代码如下

import com.tensquare.qa.client.impl.BaseClientImpl;
import entity.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 类名称:BaseClient
 * 类描述: 模块调用的接口
 *
 * @author: taohongchao
 * 创建时间:2019/2/17 10:26
 * Version 1.0
 */
@FeignClient(value = "tensquare-base",fallback = BaseClientImpl.class)
public interface BaseClient {

    /**
     * 方法名: findById
     * 方法描述: 根据id查询标签
     * 修改日期: 2019/1/6 15:20
     * @param labelId
     * @return entity.Result
     * @author taohongchao
     * @throws
     */
    @RequestMapping(value = "/label/{labelId}",method = RequestMethod.GET)
    public Result findById(@PathVariable("labelId") String labelId);
}

4.测试运行

先起 Eureka的服务. 接着启动tensquare_qa 9003端口. 不启动tensquare_base,
再次发送如下的请求
http://localhost:9003/problem/label/1, 响应的数据如下,代表调用的服务失败,走的熔断器的代码

当再次开启tensquare_base服务, 不重启tensquare_qa 服务时, 响应的数据如下. 代表服务正常了.
说明熔断器能够动态的进行切换,当调用的服务正常时,走调用服务的代码,当服务失效时,走熔断器的代码.

猜你喜欢

转载自blog.csdn.net/qq_33229669/article/details/87889998