【SpringCloud】Hystrix 사용

Hystrix 중요한 개념

https://github.com/Netflix/Hystrix/wiki/사용 방법
https://github.com/Netflix/Hystrix

  1. 서비스 저하: 서버가 사용 중입니다. 나중에 다시 시도하십시오. 클라이언트를 기다리지 말고 즉시 친숙한 프롬프트를 반환하고 대체하십시오.
  2. 서비스 융합: 스위치 끄기, 서비스 다운그레이드 -> 추가 융합 -> 통화 링크 복원
  3. 서비스 흐름 제한: 높은 동시성 및 기타 작업을 엄격히 금지합니다. 떼를 지어 몰려드는 것을 엄격히 금지하고, 모두가 초당 N씩 줄을 서서 질서 있게 진행합니다.

사용

포엠

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

스타트업 수업

@EnableHystrix

YML

feign:
  hystrix:
    enabled: true

package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentService
{
    
    
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
    
    
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")
    })
    public String paymentInfo_TimeOut(Integer id)
    {
    
    
        //int age = 10/0;
        try {
    
     TimeUnit.MILLISECONDS.sleep(3000); } catch (InterruptedException e) {
    
     e.printStackTrace(); }
        return "线程池:  "+Thread.currentThread().getName()+"success";
    }
    public String paymentInfo_TimeOutHandler(Integer id)
    {
    
    
        return "线程池:  "+Thread.currentThread().getName()+"business"+id;
    }

    //=====服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
    
    
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
    
    
        if(id < 0)
        {
    
    
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
    
    
        return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~   id: " +id;
    }

}

글로벌 폴백

@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")

예: Hystrix를 구성하지 않는 메소드는 @DefaultProperties의 메소드를 사용합니다.

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystirxController
{
    
    
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id)
    {
    
    
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
    
    
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")
    })
    //@HystrixCommand
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {
    
    
        int age = 10/0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }
    public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id)
    {
    
    
        return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }

    // 下面是全局fallback方法
    public String payment_Global_FallbackMethod()
    {
    
    
        return "Global异常处理信息,请稍后再试,/(ㄒoㄒ)/~~";
    }
}

서비스 성능이 저하되고, 클라이언트가 서버를 호출하고, 서버가 충돌하거나 종료됩니다.

이상:

  1. 달리다
  2. 타임아웃
  3. 중단 시간

인터페이스 Feign은 서비스 인터페이스를 호출합니다.

@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT" ,fallback = PaymentFallbackService.class)
public interface PaymentHystrixService
{
    
    
    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}

서비스 구현 클래스에는 Feign 호출이 실패할 때 구현 클래스의 메서드를 호출하는 최종 결과가 있습니다.

@Component
public class PaymentFallbackService implements PaymentHystrixService
{
    
    
    @Override
    public String paymentInfo_OK(Integer id)
    {
    
    
        return "-----PaymentFallbackService fall";
    }

    @Override
    public String paymentInfo_TimeOut(Integer id)
    {
    
    
        return "-----PaymentFallbackService fall TimeOut";
    }
}

이때 서버 제공자는 다운되었으나
서버를 끊거나 죽이지 않고 클라이언트가 서버를 사용할 수 없을 때 프롬프트 정보를 얻을 수 있도록 서비스 다운그레이드 처리를 수행했습니다.

서비스 회로 차단기

서비스 저하 -> 서킷 브레이커 -> 호출 링크 복원
노드 마이크로서비스 호출 응답이 정상인 것으로 감지되면 호출 링크를 복원합니다.
Spring Cloud 프레임워크에서 서킷 브레이커 메커니즘은 Hystrix를 통해 구현됩니다. Hystrix는 마이크로서비스 간의 호출 상태를 모니터링합니다.
실패한 호출이 특정 임계값에 도달하면 기본값은 5초 내에 20번의 실패 호출이며 회로 차단기 메커니즘이 활성화됩니다. 회로 차단기 메커니즘의 주석은 @HystrixCommand입니다.

@Service
public class PaymentService
{
    
    	
	//=====服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
    
    
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
    
    
        if(id < 0)
        {
    
    
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
    
    
        return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~   id: " +id;
    }
}

@HystrixCommand의 commandProperties 매개변수

HystrixCommandProperties카테고리 찾기

Hystrix 실행 프로세스

여기에 이미지 설명을 삽입하세요.

서비스 모니터링 hystrixDashboard

포엠

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

HystrixDashboardMain9001+ 새 주석 @EnableHystrixDashboard
참고:

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001
{
    
    
    public static void main(String[] args) {
    
    
            SpringApplication.run(PaymentHystrixMain8001.class, args);
    }


    /**
     *此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑
     *ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
     *只要在自己的项目里配置上下面的servlet就可以了
     */
    @Bean
    public ServletRegistrationBean getServlet() {
    
    
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

추천

출처blog.csdn.net/qq_45742250/article/details/132340244