1.Hystrix是什么
Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
“断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。
2.Hystrix能做什么
2.1 服务降级
当请求超时,服务器宕机,代码问题导致服务器异常等问题导致客户端不能正常调用业务逻辑时我们需要有一个兜底的方法,类似于if()else if()else;这个兜底的方法就是else。
2.1.1构建环境
测试需要搭建eureka服务器,一个业务逻辑服务,一个消费者服务。
首先构建eureka服务器
1.使用maven导入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
2.编写application.yml配置文件
server:
port: 7001
eureka:
instance:
hostname: localhost
client:
#false表示不向服务注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责是维护服务实例,并不需要去检索服务
fetch-registry: false
service-url:
#设置与eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://localhost:7001/eureka/ #单机
3.编写主启动类,在主启动类上添加@EnableEurekaServe注解,使eureka服务生效。
@SpringBootApplication
@EnableEurekaServer
public class EurekaServer7001 {
public static void main(String[] args) {
SpringApplication.run(EurekaServer7001.class,args);
}
}
接下来构建业务逻辑服务
1.使用maven导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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>
2.编写application.yml配置文件
server:
port: 8001
spring:
application:
name: cloud-provider-hystrix-payment
eureka:
client:
#false表示不向服务注册中心注册自己
register-with-eureka: true
#false表示自己端就是注册中心,我的职责是维护服务实例,并不需要去检索服务
fetch-registry: true
service-url:
#设置与eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://localhost:7001/eureka/ #单机
3.编写主启动类。需要加上@EnableEurekaClient注解使eureka服务生效,@EnableCircuitBreaker注解使hystrix服务生效。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentHystrixMain8001.class,args);
}
@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;
}
}
4.编写service层
@Service
public class PaymentService {
public String paymentInfo_OK(Integer id)
{
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_OK,id: "+id+"\t"+"O(∩_∩)O";
}
public String paymentInfo_TimeOut(Integer id)
{
int timeNum=2;
//int age=10/0;
try {
TimeUnit.SECONDS.sleep(timeNum);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"耗时"+timeNum+"s";
}
}
5.编写controller调用service
@RestController
@Slf4j
public class PaymentController {
@Resource
PaymentService paymentService;
@GetMapping("/payment/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable("id") Integer id)
{
String s = paymentService.paymentInfo_OK(id);
log.info("***************result: "+s);
return s;
}
@GetMapping("/payment/hystrix/timeout/{id}")
})
public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
{
String s = paymentService.paymentInfo_TimeOut(id);
log.info("***************result: "+s);
return s;
}
}
最后编写消费者
1.使用maven导入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.cj.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</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>
服务调用使用的是openfeign。
2.编写application.yml
server:
port: 80
eureka:
client:
#false表示不向服务注册中心注册自己
register-with-eureka: false
#false表示自己端就是注册中心,我的职责是维护服务实例,并不需要去检索服务
fetch-registry: true
service-url:
#设置与eureka Server 交互的地址查询服务和注册服务都需要依赖这个地址
defaultZone: http://localhost:7001/eureka/ #单机
3.编写主启动类
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class OrderHystrixMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderHystrixMain80.class,args);
}
}
4.编写service类。
由于使用openfeign调用8001的微服务,所以需要编写service接口,一定要加入组件到ioc容器。
@Component
@FeignClient(value = "cloud-provider-hystrix-payment",fallback = PaymentFallBackService.class)
public interface PaymentService {
@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);
}
5.编写controller调用service类
@RestController
public class OrderController {
@Resource
private PaymentService paymentService;
@GetMapping("/consumer/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable Integer id)
{
return paymentService.paymentInfo_OK(id);
}
@GetMapping("/consumer/hystrix/timeout/{id}")
public String paymentInfo_TimeOut(@PathVariable Integer id)
{
return paymentService.paymentInfo_TimeOut(id);
}
}
2.1.2 在8001业务逻辑服务中使用
1.在service层的paymentInfo_TimeOut()方法上添加注解,代码如下:
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
})
public String paymentInfo_TimeOut(Integer id)
{
int timeNum=5;
//int age=10/0;
try {
TimeUnit.SECONDS.sleep(timeNum);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"耗时"+timeNum+"s";
}
fallbackMethod表示降级调用的方法。3000代表了这个业务逻辑的最长处理时间不能超过3s否则调用降级方法paymentInfo_TimeOutHandler。业务内容就是让这个业务逻辑处理5s,来完成超时测试。
2.编写paymentInfo_TimeOutHandler方法:
public String paymentInfo_TimeOutHandler(Integer id)
{
return "线程池: "+Thread.currentThread().getName()+" paymentInfo_TimeOut,id: "+id+"\t"+"/(ㄒoㄒ)/~~";
}
3.启动7001,8001服务进行测试。这种写法在消费端照样可以写,不一定非要写在8001端。需要注意的是,在消费者端使用时需要开启feign.hystrix.enable=true;
4.上述写法会让每个业务逻辑的降级都重新编写对应的降级方法,我们可以编写一个全局的降级方法,使得每个业务逻辑降级时都调用我们编写的默认的降级方法。下面的测试在消费者80端进行。
2.1.3如何使用默认的服务降级方法
1.编写默认的服务降级方法:payment_Global_FallbackMethod
public String payment_Global_FallbackMethod()
{
return "全局通用的fallback";
}
2.在当前类上添加注解@DefaultProperties(defaultFallback = “payment_Global_FallbackMethod”)
@RestController
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderController {
@Resource
private PaymentService paymentService;
@GetMapping("/consumer/hystrix/ok/{id}")
public String paymentInfo_OK(@PathVariable Integer id)
{
return paymentService.paymentInfo_OK(id);
}
@GetMapping("/consumer/hystrix/timeout/{id}")
@HystrixCommand
public String paymentInfo_TimeOut(@PathVariable Integer id)
{
return paymentService.paymentInfo_TimeOut(id);
}
public String payment_Global_FallbackMethod()
{
return "全局通用的fallback";
}
}
3.在当前类的其它方法上增加@HystrixCommand注解即可设置其默认降级方法为 payment_Global_FallbackMethod;
2.1.3 降级方法的统一编写实现解耦
在使用openfeign时会编写一个service层的接口,这时我们需要继承这个接口,并实现其中的方法并且加入到ioc容器中。
@Component
public class PaymentFallBackService implements PaymentService{
@Override
public String paymentInfo_OK(Integer id) {
return "************paymentInfo_OK**************";
}
@Override
public String paymentInfo_TimeOut(Integer id) {
return "*****************paymentInfo_TimeOut********************";
}
}
在service接口上的@FeignClient注解中添加降级方法的属性即可,代码如下:
@Component
@FeignClient(value = "cloud-provider-hystrix-payment",fallback = PaymentFallBackService.class)
public interface PaymentService {
@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);
}
service接口中每个方法对应的降级方法就是其实现类重写的方法。
2.2 服务熔断
2.2.1 是什么
熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错不可用或者响应时间太长时,
会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。
当检测到该节点微服务调用响应正常后,恢复调用链路。
在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,
当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是@HystrixCommand。
2.2.2怎么使用
在8001端中的service中新增一个方法并添加注解
@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;
}
启动测试。