SpringCloud入门(4)Hystrix

经过前3节的SpringCloud学习,了解了服务的提供者可能不止有一个端口,在以后的真正的工作中可能还不止有一个微服务来提供服务。如果服务崩掉,如果没有措施,会导致很严重的损失。

就比如如果提供的是购物服务,总不可能让顾客不买东西。还有生活中最常见的例子是当家庭某个电器短路的时候,为了保护整体电器,保险丝就会进行熔断。

Hystrix的诞生就是为了解决这个问题。

1 引入Hystrix

建立hystrix父模块,修改父模块pom文件使其子模块都导入了依赖,方便以后操作。

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
</dependencies>

随后在父模块下新建一个hystrix-consume9301 子模块,最后的项目结构目录如下:

SpringCloud入门(4)Hystrix

2 主启动类和配置文件

配置文件:

spring:
  application:
    name: hystrix-consume9301
server:
  port: 9301

eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8001/eureka/
  instance:
    instance-id: hystrix-consume9301

其实配置文件简单来说都是一样的,一直重复写出来就是为了大家方便cv复现

主启动类:

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix  //开启Hystrix
@RestController  //开启业务类
public class HystrixConsume9301 {
    
    public static void main(String[] args) {
        SpringApplication.run(HystrixConsume9301.classargs);
    }

}

3 业务类

再次强调是为了方便入门,直接在主启动类中编写业务类,这是「不规范」的。

为了能够进行服务间的调用,在入门Eureka的时候也说到了利用RestTemplate 即可,所以需要添加一个config类把RestTemplate 注入到Spring容器中。

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced  //开启负载均衡功能,加了此注解才能通过服务名来访问服务
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

回过来看主启动类

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix  //开启Hystrix
@RestController  //开启业务类
public class HystrixConsume9301 {
    
    public static void main(String[] args) {
        SpringApplication.run(HystrixConsume9301.classargs);
    }
 
    //服务名字
    final String PROVIDE_URL = "http://eureka-provide";

    RestTemplate restTemplate;

    public HystrixConsume9301(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/hystrix/consume")
    @HystrixCommand(fallbackMethod = "getInfoFallback"//开启降级服务
    public String getInfo() {
        return "i am hystrix consumer, but actually invoke provide service: [" + restTemplate.getForObject(PROVIDE_URL + "/eureka/provide", String.class) + "]";
    }

    public String getInfoFallback() {
        return "hello, something wrong, i am getInfo fallback method";
    }


}

其它一切都一样,只不过是在相应的业务方法中添加了@HystrixCommand 注解,该注解中的fallbackMethod 声明的是服务降级后回调的是哪个方法。

4 测试

开启Eureka服务注册中心EurekaServer8001,服务提供者EurekaProvide7001,[7002, 7003],开启HystrixConsume9301

SpringCloud入门(4)Hystrix

访问http://localhost:9301/hystrix/consume,正常情况下如图所示

SpringCloud入门(4)Hystrix

但是当我们「把所有的服务提供者EurekaProvide7001停掉以模拟服务挂掉的情况」,测试结果如图所示。可以看到服务并没有报错,确实降级调用我们想要调用的方法。

SpringCloud入门(4)Hystrix

5 扩展

对于扩展方面,这里就稍微提下@HystrixProperty 注解,直接看例子。

通过sleep() 函数来模拟服务提供端延迟提供服务

首先需要修改的是「服务提供端的代码,服务提供端的代码,服务提供端的代码」「也就是本系列第一篇文章中的eureka-client-provide7001子模块项目」

@SpringBootApplication
@RestController
@EnableEurekaClient
public class EurekaProvide7001 {

    @Value("${server.port}")
    int port;

    @GetMapping("/eureka/provide")
    public String getInfo() {
        return "hello, i am eureka provide, the provide service. My port: " + port;
    }
 
    //下面是添加的内容
    @GetMapping("/eureka/delayProvide")
    public String delayGetInfo() throws InterruptedException {
        Thread.sleep(3000);
        //延迟3秒才执行真正的业务逻辑
        return "hello, delay to do something";
    }
    public static void main(String[] args) {
        SpringApplication.run(EurekaProvide7001.classargs);
    }
}

然后修改「Hystrix消费端的代码」

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
@RestController
public class HystrixConsume9301 {
    public static void main(String[] args) {
        SpringApplication.run(HystrixConsume9301.classargs);
    }

    final String PROVIDE_URL = "http://eureka-provide";

    RestTemplate restTemplate;

    public HystrixConsume9301(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    //省略一部分

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    }, fallbackMethod = "getPropFallback")
    @GetMapping("hystrix/normalConsume")
    public String getNormalConsumeInfo() {
        long start = System.currentTimeMillis();
        String res = restTemplate.getForObject(PROVIDE_URL + "/eureka/delayProvide", String.class);
        long end = System.currentTimeMillis();
        res += "[cost time: " + (end - start) + "]";
        return res;
    }

    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    }, fallbackMethod = "getPropFallback")
    @GetMapping("hystrix/timeoutConsume")
    public String getTimeoutConsumeInfo() {
        long start = System.currentTimeMillis();
        String res = restTemplate.getForObject(PROVIDE_URL + "/eureka/delayProvide", String.class);
        long end = System.currentTimeMillis();
        res += "[cost time: " + (end - start) + "]";
        return res;
    }

    public String  getPropFallback() {
        return "timeout, fallback method, do something.";
    }

}

@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000" 主要表示的是在规定的时间(5000)如果能调用服务,那么就不fallback。

上面的服务是延迟了3000ms执行业务,然后我设置了一个回调阈值是5000ms,一个是2000ms。

开始测试前注意「把刚才停掉的服务提供者EurekaProvide7001开启」 ,模拟的是延迟调用服务,并不是服务挂掉了。首先访问http://localhost:9301/hystrix/normalConsume:

SpringCloud入门(4)Hystrix

可以看到转圈圈是大概3s后有响应,同时通过消耗的时间也可以看出。

那么当访问「超时接口」后http://localhost:9301/hystrix/timeoutConsume:

SpringCloud入门(4)Hystrix

可以看到转圈圈是大概2s后有响应,并且调用的是fallback方法,并不是服务提供方法。上种情况转3s是因为服务调用是3s,这种情况转2s是因为我们设置了回调阈值是2s,到2s后还没调用服务就调用fallback。

6 Hystrix Dashboard

这是一款可视化的监控,主要是帮助我们直观地看到了Hystrix Command有关响应的一些指标

引入依赖

「修改hystrix-consume9301子模块下的pom文件」 ,往其中添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
    </dependency>
</dependencies>

修改主启动类,增加Bean

@SpringBootApplication
@EnableEurekaClient
@EnableHystrixDashboard  //开启可视化界面,其实就是多加了这个注解
@EnableHystrix
@RestController
public class HystrixConsume9301 {
    
}

此时可以启动主启动类来访问http://localhost:9301/hystrix

SpringCloud入门(4)Hystrix

看到这个界面说明配置成功,值得注意的是我们还需要增加一个Bean的配置类才能够正确运行,在config包下新建一个类ServletRegisterBeanConfig

@Configuration
public class ServletRegisterBeanConfig {
    @Bean(name = "registerBean")
    public ServletRegistrationBean getServlet(){

        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();

        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);

        registrationBean.setLoadOnStartup(1);

        registrationBean.addUrlMappings("/actuator/hystrix.stream");

        registrationBean.setName("HystrixMetricsStreamServlet");


        return registrationBean;
    }
}

最后重新启动HystrixConsume9301主启动类,再次访问http://localhost:9301/hystrix,然后填入需要监控的stream

SpringCloud入门(4)Hystrix

当点击监控流后,会发现dashboard界面和控制台同时报错

SpringCloud入门(4)Hystrix
SpringCloud入门(4)Hystrix

修改配置文件

按照控制台报错修改控制文件,加入

hystrix:
  dashboard:
    proxy-stream-allow-list: localhost

重启项目,此时重复上述操作可以看到正确运行,等待连接

SpringCloud入门(4)Hystrix

测试

开启Eureka服务注册中心EurekaServer8001,服务提供者EurekaProvide7001,[7002, 7003],开启HystrixConsume9301 。访问消费接口http://localhost:9301/hystrix/consume ,http://localhost:9301/hystrix/normalConsume ,http://localhost:9301/hystrix/timeoutConsume,看下能不能监控到。

SpringCloud入门(4)Hystrix

可以看到确实能够实时监控到请求,并且有对应的指标。

「创作不易,如果对你有帮助,欢迎点赞,收藏和分享啦!」



原文始发于微信公众号(咖啡编程):SpringCloud入门(4)Hystrix

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/23273.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!