目录
全局降级 fallback——defaultFallback
hystrix一般作用于服务提供方,也可以作用在消费方
能干嘛?
服务降级,服务熔断,接近实时的监控
服务降级:服务降级是从整个系统的负荷情况出发和考虑的,对某些负荷会比较高的情况,为了预防某些功能(业务场景)出现负荷过载或者响应慢的情况,在其内部暂时舍弃对一些非核心的接口和数据的请求,而直接返回一个提前准备好的fallback(退路)错误处理信息。这样,虽然提供的是一个有损的服务,但却保证了整个系统的稳定性和可用性。
服务熔断:某服务出现不可用或响应超时的情况时,为了防止整个系统出现雪崩,暂时停止对该服务的调用。
服务降级
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
服务端配置Hystrix
启动类
添加@EnableCircuitBreaker,开启熔断器功能
package com.qfedu;
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
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class,args);
}
}
service
在方法存在超时或者异常等会使服务器一直等待或者直接报异常时添加@HystrixCommand(fallbackMethod="回调方法",),如果该方法报异常或者超时,则会执行fallbackMethod的方法
package com.qfedu.service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* @ClassName PaymentService
* @Description TODO
* @Author huocarry
* @Date 2023/1/5 17:20
* @Version 1.0
**/
@Service
public class PaymentService {
public String paymentInfo_OK(Integer id) {
return "线程池: " + Thread.currentThread().getName() + " paymentInfo_OK,id: " + id + "\t" + "O(∩_∩)O哈哈~";
}
@HystrixCommand(fallbackMethod ="paymentInfo_TimeoutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfo_Timeout(Integer id) {
int timeNumber = 5;
try {
TimeUnit.SECONDS.sleep(timeNumber);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: " + Thread.currentThread().getName() + " paymentInfo_Timeout,id: " + id + "\t" + "耗时" + timeNumber + "s";
}
public String paymentInfo_TimeoutHandler(Integer id){
return "线程池: " + Thread.currentThread().getName() + " paymentInfo_Timeout,id: " + id +"o(╥﹏╥)o" ;
}
}