Back to Javatutorial

SpringCloudHystrix

docs/Spring全家桶/SpringCloud/SpringCloudHystrix.md

1.0.028.2 KB
Original Source

΢ܹУһӦɶɣЩ֮໥ϵ۸ӡ

һ΢ϵͳд ABCDEF ȶǵϵͼ

ͼ1ϵ

ͨ£һûҪϲɡͼ 1 ʾз񶼴ڿ״̬ʱ 1 Ҫ ADEF ĸɣ 2 Ҫ BED ɣ 3 Ҫ÷ CFED ĸɡ

E ϻӳʱ

  1. ʹз񶼿ãڷ E IJãôû 123 ᴦ״̬ȴ E Ӧڸ߲ij£ᵼ߳ԴڶʱѸĴ
  2. ڷ E BD Լ F Ҳᴦ߳״̬ȴ E ӦЩIJá
  3. BD F ķ A ͷ C Ҳᴦ߳״̬Եȴ D ͷ F Ӧ· A ͷ C Ҳá

Ϲ̿Կ΢ϵͳһֹʱϻŷĵ·ϵͳзӣյ΢ϵͳ̱ǡѩЧӦΪ˷ֹ¼ķ΢ܹˡ۶һϵзݴͱơ

۶

۶Circuit BreakerһԴѧеĵ·֪ʶǵ·ֹʱѸжϵԴԱ·İȫ

΢۶ Martin Fowler Circuit Breakerһѧе۶ƣ΢ܹе۶ܹijϺ÷һԤڵġɴĽӦFallBackdzʱĵȴ׳÷޷쳣ͱ֤˷÷̲߳ᱻʱ䡢Ҫռã΢ϵͳеӣֹϵͳѩЧӦķ

Spring Cloud Hystrix

Spring Cloud Hystrix һķݴ뱣Ҳ Spring Cloud Ҫ֮һ

Spring Cloud Hystrix ǻ Netflix ˾ĿԴ Hystrix ʵֵģṩ۶ܣܹЧֲֹʽ΢ϵͳгϣ΢ϵͳĵԡSpring Cloud Hystrix з񽵼۶ϡ̸߳롢󻺴桢ϲԼʵʱϼصǿܡ

Hystrix [h?st'r?ks]ĺǺıϳ˼̣ʹӵǿұ Spring Cloud Hystrix Ϊһݴ뱣Ҳ÷ӵұҲ˽ϷΪ硱

΢ϵͳУHystrix ܹʵĿ꣺

  • ߳ԴֹĹϺľϵͳе߳Դ
  • ʧܻij˹ϣ÷÷һֱȴֱӷʧܡ
  • ṩFallBackʧܺṩһƺõĽͨһ׷ʧܺ󼴵ø÷
  • ֹɢʹ۶ϻƣֹɢ
  • عṩ۶ϼ Hystrix Dashboardʱ۶״̬

Hystrix 񽵼

Hystrix ṩ˷񽵼ܣܹ֤ǰϵӰ죬߷Ľ׳ԡ

񽵼ʹó 2 ֣

  • ڷѹʱʵҵһЩҪķвԵز򵥴ӶͷŷԴԱ֤ķ
  • ijЩ񲻿ʱΪ˱ⳤʱȴɷ񿨶ٻѩЧӦִбõĽ߼̷һѺõʾԱҵӰ졣

ǿͨд HystrixCommand getFallBack() HystrixObservableCommand resumeWithFallback() ʹַ֧񽵼

Hystrix 񽵼 FallBack ȿԷڷ˽УҲԷڿͻ˽С

Hystrix ³½з񽵼

  • ʱ
  • ۶ڴ״̬
  • ̳߳Դľ

ʾ1

Ǿͨһֱʾ Hystrix ˷񽵼Ϳͻ˷񽵼

˷񽵼

1. spring-cloud-demo2 ´һΪ micro-service-cloud-provider-dept-hystrix-8004 ķṩߣ pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--pom-->
    <parent>
        <artifactId>spring-cloud-demo2</artifactId>
        <groupId>net.biancheng.c</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>net.biancheng.c</groupId>
    <artifactId>micro-service-cloud-provider-dept-hystrix-8004</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>micro-service-cloud-provider-dept-hystrix-8004</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring Boot ļģ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- eureka ͻ-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--hystrix -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2. · /resources Ŀ¼һļ application.yml¡


spring:
  application:
    name: microServiceCloudProviderDeptHystrix  #΢ƣⱩ©΢ƣʮҪ

server:
  port: 8004
########################################### Spring cloud Զƺ ip ַ###############################################
eureka:
  client: #ͻעᵽ eureka б
    service-url:
      #defaultZone: http://eureka7001:7001/eureka  #ַ 7001ע application.yml б¶עַ 棩
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  #עᵽ Eureka Ⱥ
  instance:
    instance-id: spring-cloud-provider-8004 #ԶϢ
    prefer-ip-address: true  #ʾ· ip ַ
#####################spring cloud ʹ Spring Boot actuator Ϣ###########################################
# Spring Boot 2.50 actuator ˴Ľڵ㣬ֻ¶ heath ڵ㣬ã*Ϊ˿еĽڵ
management:
  endpoints:
    web:
      exposure:
        include: "*"   # * yaml ļڹؼ֣Ҫ
info:
  app.name: micro-service-cloud-provider-dept-hystrix
  company.name: c.biancheng.net
  build.aetifactId: @project.artifactId@
  build.version: @project.version@

3. net.biancheng.c.service ´һΪ DeptService Ľӿڣ¡


package net.biancheng.c.service;

public interface DeptService {

    // hystrix ۶ʾ ok
    public String deptInfo_Ok(Integer id);

    //hystrix ۶ʱ
    public String deptInfo_Timeout(Integer id);
}

4. net.biancheng.c.service.impl £ DeptService ӿڵʵ DeptServiceImpl¡

package net.biancheng.c.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import net.biancheng.c.service.DeptService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("deptService")
public class DeptServiceImpl implements DeptService {

    @Override
    public String deptInfo_Ok(Integer id) {
        return "̳߳أ" + Thread.currentThread().getName() + "  deptInfo_Ok,id:   " + id;
    }

    //һ÷ʧܲ׳쳣Ϣ󣬻Զ  @HystrixCommand עע fallbackMethod ָķ
    @HystrixCommand(fallbackMethod = "dept_TimeoutHandler",
            commandProperties =
                    //涨 5 ھͲУ 5 ͱָķ
                    {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")})
    @Override
    public String deptInfo_Timeout(Integer id) {
        int outTime = 6;
        try {
            TimeUnit.SECONDS.sleep(outTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "̳߳أ" + Thread.currentThread().getName() + "  deptInfo_Timeout,id:   " + id + "  ʱ: " + outTime;
    }

    // ֹϺ󣬵ø÷Ѻʾ
    public String dept_TimeoutHandler(Integer id) {
       return  "CϵͳæԺԣ"+"̳߳أ" + Thread.currentThread().getName() + "  deptInfo_Timeout,id:   " + id;
    }
}

ǿԿ deptInfo_Timeout() ʹ @HystrixCommand ע⣬ע˵£

  • fallbackMethod ָ
  • execution.isolation.thread.timeoutInMilliseconds óʱʱķֵֵڿУִн
  1. net.biancheng.c.controller ´һΪ DeptController Controller ࣬¡

package net.biancheng.c.controller;

import lombok.extern.slf4j.Slf4j;
import net.biancheng.c.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Value("${server.port}")
    private String serverPort;

    @RequestMapping(value = "/dept/hystrix/ok/{id}")
    public String deptInfo_Ok(@PathVariable("id") Integer id) {
        String result = deptService.deptInfo_Ok(id);
        log.info("˿ںţ" + serverPort + " result:" + result);
        return result + "   ˿ںţ" + serverPort;
    }

    // Hystrix ʱ
    @RequestMapping(value = "/dept/hystrix/timeout/{id}")
    public String deptInfo_Timeout(@PathVariable("id") Integer id) {
        String result = deptService.deptInfo_Timeout(id);
        log.info("˿ںţ" + serverPort + " result:" + result);
        return result + "   ˿ںţ" + serverPort;
    }

}

6. micro-service-cloud-provider-dept-hystrix-8004 ϣʹ @EnableCircuitBreaker ע⿪۶ܣ¡



package net.biancheng.c;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient // Eureka ͻ˹
@EnableCircuitBreaker //۶
public class MicroServiceCloudProviderDeptHystrix8004Application {

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

}

7. עģEureka ServerȺ micro-service-cloud-provider-dept-hystrix-8004ʹʡhttp://eureka7001.com:8004/dept/hystrix/ok/1ͼ

ͼ2Hystrix

8. ʹʡhttp://eureka7001.com:8004/dept/hystrix/timeout/1ͼ

ͼ3Hystrix ˷񽵼

ͻ˷񽵼

ͨ£Ƕڿͻ˽з񽵼ͻ˵õķ˵ķ񲻿ʱͻֱӽз񽵼̱߳ʱ䡢Ҫռá

ͻ˷񽵼¡

1. micro-service-cloud-consumer-dept-feign pom.xml Hystrix ¡



<!--hystrix -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  1. micro-service-cloud-consumer-dept-feign application.yml ãͻ˵ Hystrix ܡ

feign:
  hystrix:
    enabled: true #ͻ hystrix

3. net.biancheng.c.service £һΪ DeptHystrixService ķ󶨽ӿڣ micro-service-cloud-provider-dept-hystrix-8004 ṩķӿڽа󶨣¡


package net.biancheng.c.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Component
@FeignClient(value = "MICROSERVICECLOUDPROVIDERDEPTHYSTRIX")
public interface DeptHystrixService {
    @RequestMapping(value = "/dept/hystrix/ok/{id}")
    public String deptInfo_Ok(@PathVariable("id") Integer id);

    @RequestMapping(value = "/dept/hystrix/timeout/{id}")
    public String deptInfo_Timeout(@PathVariable("id") Integer id);
}

4. net.biancheng.c.controller ´һΪ HystrixController_Consumer Controller ¡

package net.biancheng.c.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;;
import lombok.extern.slf4j.Slf4j;
import net.biancheng.c.service.DeptHystrixService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public class HystrixController_Consumer {

    @Resource
    private DeptHystrixService deptHystrixService;

    @RequestMapping(value = "/consumer/dept/hystrix/ok/{id}")
    public String deptInfo_Ok(@PathVariable("id") Integer id) {
        return deptHystrixService.deptInfo_Ok(id);
    }

    //ڿͻ˽н
    @RequestMapping(value = "/consumer/dept/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "dept_TimeoutHandler") //ΪָרĻ˷
    public String deptInfo_Timeout(@PathVariable("id") Integer id) {
        String s = deptHystrixService.deptInfo_Timeout(id);
        log.info(s);
        return s;
    }

    // deptInfo_Timeout ר fallback 
    public String dept_TimeoutHandler(@PathVariable("id") Integer id) {
        log.info("deptInfo_Timeout ѱ");
        return "CϵͳæԺԣͻ deptInfo_Timeout רĻ˷";
    }
}

5. ļ appliction.yml ãڿͻʱʱ䡣

######################### Ribbon ͻ˳ʱ ###################################
ribbon:
  ReadTimeout: 6000 #õʱ䣬״£õʱ
  ConnectionTimeout: 6000 #Ӻ󣬷ȡԴʱ
######################ʱʱ##########################
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 7000
####################þ巽ʱʱ Ϊ 3 ########################
    DeptHystrixService#deptInfo_Timeout(Integer):
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000

ļijʱʱʱҪע 2 㣺

1Hystrix Ϊ󣨷óʱʱ䣨λΪ룩ʱ򴥷ȫֵĻ˷д

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=mmm

2Hystrix Ϊijضķ󣨷óʱʱ䣬ʽ£

hystrix.command.xxx#yyy(zzz).execution.isolation.thread.timeoutInMilliseconds=mmm

ʽ˵£

  • xxxΪ÷񷽷ƣͨΪ󶨽ӿڵƣ DeptHystrixService ӿڡ
  • yyy񷽷 deptInfo_Timeout()
  • zzzڵIJͣ IntegerString ȵ
  • mmmҪõijʱʱ䣬λΪ루1 =1000 룩

6. micro-service-cloud-consumer-dept-feign ϣʹ @EnableHystrix ע⿪ͻ Hystrix ܣ¡


package net.biancheng.c;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients // OpenFeign 
@EnableHystrix // Hystrix
public class MicroServiceCloudConsumerDeptFeignApplication {

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

7. ޸ micro-service-cloud-provider-dept-hystrix-8004 DeptServiceImpl Ĵ룬 deptInfo_Timeout() ʱ޸Ϊ 4 루Сڳʱʱ 5 룩Ա֤¡

//һ÷ʧܲ׳쳣Ϣ󣬻Զ  @HystrixCommand עע fallbackMethod ָķ
@HystrixCommand(fallbackMethod = "dept_TimeoutHandler",
        commandProperties =
                //涨 5 ھͲУ 5 ͱָķ
                {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")})
@Override
public String deptInfo_Timeout(Integer id) {
    int outTime = 4;
    try {
        TimeUnit.SECONDS.sleep(outTime);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "̳߳أ" + Thread.currentThread().getName() + "  deptInfo_Timeout,id:   " + id + "  ʱ: " + outTime;
}

8. micro-service-cloud-provider-dept-hystrix-8004 micro-service-cloud-consumer-dept-feignʹʡhttp://eureka7001.com:8004/dept/hystrix/timeout/1ֱӵ÷˵ deptInfo_Timeout() ͼ

ͼ4Hystrix

9. ʹʡhttp://eureka7001.com/consumer/dept/hystrix/timeout/1ͼ

ͼ5Hystrix ͻ˷񽵼

ͼ 5 ԿڷĺʱΪ 4 룬˿ͻΪָijʱʱ 3 ˸÷񱻽ָĻ˷

ȫֽ

ͨķʽʵַ񽵼ʱҪҵ񷽷ý⼫пܻɴļ͡Ϊ˽⣬ǻΪҵ񷽷ָһȫֵĻ˷岽¡

1. HystrixController_Consumer ϱע @DefaultProperties ע⣬ͨ defaultFallback ָһȫֵĽ¡



@Slf4j
@RestController
@DefaultProperties(defaultFallback = "dept_Global_FallbackMethod") //ȫֵķ񽵼
public class HystrixController_Consumer {

}

2. HystrixController_Consumer УһΪ dept_Global_FallbackMethod ȫֻط¡



/**
 * ȫֵ fallback 
 * ˷ hystrix ִзͬ
 * @DefaultProperties(defaultFallback = "dept_Global_FallbackMethod") ע⣬󷽷ʹ @HystrixCommand ע
 */
public String dept_Global_FallbackMethod() {
    return "CгϵͳæԺԣͻȫֻ˷,";
}

עFallBackӦҵ񷽷ͬһУ޷Ч

3. еҵ񷽷϶ע @HystrixCommand ע⣬ǽ deptInfo_Timeout() ϵ @HystrixCommand(fallbackMethod = "dept_TimeoutHandler") ޸Ϊ @HystrixCommand ɣ¡



//ڿͻ˽н
@RequestMapping(value = "/consumer/dept/hystrix/timeout/{id}")
@HystrixCommand
public String deptInfo_Timeout(@PathVariable("id") Integer id) {
    String s = deptHystrixService.deptInfo_Timeout(id);
    log.info(s);
    return s;
}

עȫֽȼϵֻͣҵ񷽷ûָ併ʱ񽵼ʱŻᴥȫֻ˷ҵ񷽷ָԼĻ˷ôڷ񽵼ʱֱֻӴԼĻ˷ȫֻ˷

4. micro-service-cloud-consumer-dept-feignʹʡhttp://eureka7001.com/consumer/dept/hystrix/timeout/1ͼ

ͼ6ȫֻ˷

߼

ҵ񷽷ָĽȫֽǶҵ񷽷ͬһвЧҵ߼뽵߼϶ȼߡ

Ƕҵ߼뽵߼н¡

1. micro-service-cloud-consumer-dept-feign net.biancheng.c.service £½ DeptHystrixService ӿڵʵ DeptHystrixFallBackServiceͳһΪ DeptHystrixService еķṩ񽵼 ¡


package net.biancheng.c.service;
import org.springframework.stereotype.Component;
/**
* Hystrix 񽵼
* ߼
*/
@Component
public class DeptHystrixFallBackService implements DeptHystrixService {
    @Override
    public String deptInfo_Ok(Integer id) {
        return "--------------------CϵͳæԺԣ˷-----------------------";
    }
    @Override
    public String deptInfo_Timeout(Integer id) {
        return "--------------------CϵͳæԺԣ˷-----------------------";
    }
}

עʽ Spring вЧõķʽϱע @Component ע⡣

2. ڷ󶨽ӿ DeptHystrixService ע @FeignClient ע fallback ԣֵΪ DeptHystrixFallBackService.class¡

package net.biancheng.c.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
@FeignClient(value = "MICROSERVICECLOUDPROVIDERDEPTHYSTRIX", fallback = DeptHystrixFallBackService.class)
public interface DeptHystrixService {
    @RequestMapping(value = "/dept/hystrix/ok/{id}")
    public String deptInfo_Ok(@PathVariable("id") Integer id);
    @RequestMapping(value = "/dept/hystrix/timeout/{id}")
    public String deptInfo_Timeout(@PathVariable("id") Integer id);
}

3. micro-service-cloud-consumer-dept-feignȻرշ micro-service-cloud-provider-dept-hystrix-8004ʹʡhttp://eureka7001.com/consumer/dept/hystrix/ok/1ͼ

ͼ7Hystrix ˷

Hystrix ۶

۶ϻΪӦѩЧӦֵһ΢·ơ

΢ϵͳеij΢񲻿ûӦʱ̫ʱΪ˱ϵͳԣ۶ʱжԸ÷ĵãٷһѺõĴӦ۶״̬õģھһʱ۶ٴμ΢Ƿָָָ·

۶״̬

۶ϻ漰۶״̬

  • ۶Ϲر״̬Closedʱ۶ڹر״̬÷ضԷеá
  • ۶Ͽ״̬OpenĬ£ڹ̶ʱڽӿڵóʴﵽһֵ 50%۶۶Ͽ״̬۶״̬󣬺Ը÷ĵöᱻжϣ۶ִбصĽFallBack
  • ۶״̬Half-Open ۶Ͽһʱ֮۶۶״̬ڰ۶״̬£۶᳢Իָ÷Էĵãø÷񣬲óɹʡɹʴﵽԤڣ˵ѻָ۶ر״̬ɹԾɺܵͣ½۶Ͽ״̬

۶״̬֮תϵͼ

ͼ8۶״̬ת

Hystrix ʵ۶ϻ

Spring Cloud У۶ϻͨ Hystrix ʵֵġHystrix ΢õ״ʧܵõһʱ 5 ʧ 20 Σͻ۶ϻơ

Hystrix ʵַ۶ϵIJ£

  1. ĵóʴﵽ򳬹 Hystix 涨ıʣĬΪ 50%۶۶Ͽ״̬
  2. ۶۶Ͽ״̬Hystrix һʱ䴰ʱ䴰ڣ÷Ľ߼ʱ䵱ҵ߼ԭҵ߼á
  3. ٴεø÷ʱֱӵý߼ٵطʧӦԱϵͳѩ
  4. ʱ䴰ںHystrix ۶ת̬Էԭҵ߼еãóɹʡ
  5. óɹʴﵽԤڣ˵ѻָHystrix ۶Ϲر״̬ԭҵ߼ָ Hystrix ½۶Ͽ״̬ʱ䴰¼ʱظ 2 5

ʾ

Ǿͨһʵ֤ Hystrix ʵ۶ϻƵġ

1. micro-service-cloud-provider-dept-hystrix-8004 е DeptService ӿһ deptCircuitBreaker() ¡


package net.biancheng.c.service;
public interface DeptService {
    // hystrix ۶ʾ ok
    public String deptInfo_Ok(Integer id);
   
    //hystrix ۶ʱ
    public String deptInfo_Timeout(Integer id);
    // Hystrix ۶ϻư
    public String deptCircuitBreaker(Integer id);
}

2. DeptService ӿڵʵ DeptServiceImpl deptCircuitBreaker() ķʵּ˷¡

//Hystrix ۶ϰ
@Override
@HystrixCommand(fallbackMethod = "deptCircuitBreaker_fallback", commandProperties = {
        //² HystrixCommandProperties Ĭ
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), //Ƿ۶
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "1000"), //ͳʱ䴰
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), //ͳʱ䴰
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //ʱ䴰
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), //ͳʱ䴰ڣʧʴﵽ 60% ʱ۶״̬
})
public String deptCircuitBreaker(Integer id) {
    if (id < 0) {
        // id Ϊʱ׳쳣ý
        throw new RuntimeException("cid Ǹ");
    }
    String serialNum = IdUtil.simpleUUID();
    return Thread.currentThread().getName() + "\t" + "óɹˮΪ" + serialNum;
}

//deptCircuitBreaker Ľ
public String deptCircuitBreaker_fallback(Integer id) {
    return "cid Ǹ,Ժ!\t id:" + id;
}

ϴУ漰 4 Hystrix ۶ϻصҪ 4 ĺ±

metrics.rollingStats.timeInMillisecondsͳʱ䴰
circuitBreaker.sleepWindowInMillisecondsʱ䴰۶Ͽ״̬һʱ۶Զ۶״̬ʱͱΪߴڡ
circuitBreaker.requestVolumeThresholdֵͳʱ䴰ڣ뵽һHystrix ſܻὫ۶򿪽۶Ͽת̬ ֵHystrix ֵĬΪ 20ζͳʱ䴰ڣô 20 Σʹе󶼵ó۶Ҳ򿪡
circuitBreaker.errorThresholdPercentageٷֱֵͳʱ䴰ڳֵóʳһı۶Ż򿪽۶Ͽת̬ǴٷֱֵٷֱֵΪ 50ͱʾٷֱΪ 50% 30 εã 15 η˴󣬼 50% Ĵٷֱȣʱ۶ͻ򿪡

3. DeptController һ deptCircuitBreaker() ṩ񣬴¡


// Hystrix ۶
@RequestMapping(value = "/dept/hystrix/circuit/{id}")
public String deptCircuitBreaker(@PathVariable("id") Integer id){
    String result = deptService.deptCircuitBreaker(id);
    log.info("result:"+result);
    return result;
}

4. micro-service-cloud-provider-dept-hystrix-8004ʹʡhttp://eureka7001.com:8004/dept/hystrix/circuit/1ͼ

ͼ9Hystrix ʵ۶ϻ ȷʾ

5. Σôֵʡhttp://eureka7001.com:8004/dept/hystrix/circuit/-2ʹóʴڴٷֱȷֵͼ

ͼ10Hystrix ʵ۶ϻ

6. ½޸ΪΪ 3ʹʡhttp://eureka7001.com:8004/dept/hystrix/circuit/3ͼ

ͼ11Hystrix ۶Ͽ״̬

ͨͼ 11 Կ۶Ͽ״̬£ʹǴIJѾõȻ߼

7. ʡhttp://eureka7001.com:8004/dept/hystrix/circuit/3ͼ

ͼ12Hystrix ۶Ϲر״̬

ͨͼ 12 ԿȷһʺHystrix ۶Ϲر״̬

Hystrix ϼ

Hystrix ṩ׼ʵʱĵüأHystrix DashboardܣHystrix ؼ¼ͨ Hystrix ִϢͳƱʽչʾûÿִɹʧȡ

Ǿͨһʵ Hystrix Dashboard micro-service-cloud-provider-dept-hystrix-8004

1. ڸ½һΪ micro-service-cloud-consumer-dept-hystrix-dashboard-9002 ģ飬 pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-cloud-demo2</artifactId>
        <groupId>net.biancheng.c</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>net.biancheng.c</groupId>
    <artifactId>micro-service-cloud-consumer-dept-hystrix-dashboard-9002</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>micro-service-cloud-consumer-dept-hystrix-dashboard-9002</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--hystrix-dashboard ص-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>
        <!-- Spring Boot ļģ-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. micro-service-cloud-consumer-dept-hystrix-dashboard-9002 application.yml á


server:
  port: 9002  #˿ں

#http://eureka7001.com:9002/hystrix ۶ҳ
# localhost:8004//actuator/hystrix.stream صַ
hystrix:
  dashboard:
    proxy-stream-allow-list:
      - "localhost"

3. micro-service-cloud-consumer-dept-hystrix-dashboard-9002 @EnableHystrixDashboard ע⣬ Hystrix عܣ¡


package net.biancheng.c;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication
@EnableHystrixDashboard
public class MicroServiceCloudConsumerDeptHystrixDashboard9002Application {

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

}

4. micro-service-cloud-provider-dept-hystrix-8004 net.biancheng.c.config £һΪ HystrixDashboardConfig ࣬¡


package net.biancheng.c.config;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HystrixDashboardConfig {
    /**
     *  Hystrix dashboard ؽ
     * @return
     */
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/actuator/hystrix.stream");//·
        registrationBean.setName("hystrix.stream");
        return registrationBean;
    }

}

5. micro-service-cloud-consumer-dept-hystrix-dashboard-9002ʹʡhttp://eureka7001.com:9002/hystrixͼ

ͼ13Hystrix ҳ

6. micro-service-cloud-provider-dept-hystrix-8004Ϣ Hystrix ҳУͼ

ͼ14Hystrix Ϣ

7. · Monitor Stream ťת Hystrix micro-service-cloud-provider-dept-hystrix-8004 ļҳ棬ͼ

ͼ15Hystrix ΢

8. ʹηʡhttp://eureka7001.com:8004/dept/hystrix/circuit/1 http://eureka7001.com:8004/dept/hystrix/circuit/-1鿴 Hystrix ҳ棬ͼ

ͼ16Hystrix ط

ο

https://lijunyi.xyz/docs/SpringCloud/SpringCloud.html#_2-2-x-%E5%88%86%E6%94%AF https://mp.weixin.qq.com/s/2jeovmj77O9Ux96v3A0NtA https://juejin.cn/post/6931922457741770760 https://github.com/D2C-Cai/herring http://c.biancheng.net/springcloud https://github.com/macrozheng/springcloud-learning