SpringCloud之Hystrix的详细使用
1.概念
服务降级:服务器繁忙,请稍后再试,不让客户端等待,并立即返回一个友好的提示(一般发生在 程序异常,超时,服务熔断触发服务降级,线程池、信号量 打满也会导致服务降级)
服务熔断 : 达到最大服务访问后,直接拒绝访问,然后调用服务降级的方法并返回友好提示(如保险丝一样)
服务限流 : 秒杀等高并发操作,严禁一窝蜂的过来拥挤,排队进入,一秒钟N个,有序进行
***一.服务降级***
2.不使用Hystrix的项目
大致的Service和Controller层如下
***************Controller***************** package com.sky.springcloud.controller; import com.sky.springcloud.service.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController @Slf4j public class PaymentController { @Resource private PaymentService paymentService; @Value("${server.port}") private String serverport; @GetMapping("/payment/hystrix/ok/{id}") public String paymentInfo_Ok(@PathVariable("id") Integer id){ String result = paymentService.paymentInfo_ok(id); log.info("*****"+ result); return result; } @GetMapping("/payment/hystrix/timeout/{id}") public String paymentInfo_TimeOut(@PathVariable("id") Integer id){ String result = paymentService.payment_Info_TimeOut(id); } *******************Service******************** package com.sky.springcloud.service; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class PaymentServiceImpl implements PaymentService{ @Override public String paymentInfo_ok(Integer id) { return "线程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~"; public String payment_Info_TimeOut(Integer id) { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~";
在这种情况时,当通过浏览器访问 TimeOut这个方法,会三秒后返回结果,而当访问 OK 这个方法时,会直接返回结果(但是这是在访问量很少的时候,一旦访问量过多,访问OK时也会出现延迟,这里可以使用Jmeter模拟两万个访问量,如下)
使用 Jmeter 模拟后,再去访问OK,会明显出现加载的效果
3. 使用Hystrix
在主启动类添加注解
@EnableHystrix
package com.sky.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.hystrix.EnableHystrix; @SpringBootApplication @EnableEurekaClient //启用Eureka @EnableHystrix //启用Hystrix public class Payment8001 { public static void main(String[] args) { SpringApplication.run(Payment8001.class,args); } }
在原有的基础上,在Service层加上如下注解
@HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",//当服务降级时,调用payment_Info_TimeOutHandler方法 commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")//设置时间为3秒,超过三秒就为时间超限
*****************改后的Service******************* package com.sky.springcloud.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service public class PaymentServiceImpl implements PaymentService{ @Override public String paymentInfo_ok(Integer id) { return "线程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~"; } @HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") }) public String payment_Info_TimeOut(Integer id) { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } // int a = 10 / 0; return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~"; } public String payment_Info_TimeOutHandler(Integer id){ return "线程超时或异常 " + Thread.currentThread().getName(); } }
如上Service所示,如果再次访问TimeOut需要等待五秒,但是Hystrix设置的超时时间为三秒,所以当三秒后没有结果就会服务降级,从而调用TimeOutHandler这个指定 的方法来执行(或者有程序出错等情况也会服务降级)
4. 全局的Hystrix配置
@DefaultProperties(defaultFallback = “Gloub_Test”)
package com.sky.springcloud.service; import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.stereotype.Service; @Service @DefaultProperties(defaultFallback = "Gloub_Test") public class PaymentServiceImpl implements PaymentService{ @Override @HystrixCommand public String paymentInfo_ok(Integer id) { int a = 10 / 0; return "线程池:" + Thread.currentThread().getName() + "paymentInfo_Ok. id:" + id + "\t" + "~~~~~"; } @HystrixCommand(fallbackMethod = "payment_Info_TimeOutHandler",commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000") }) public String payment_Info_TimeOut(Integer id) { /* try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }*/ return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut. id:" + id + "\t" + "~~~~~"; public String payment_Info_TimeOutHandler(Integer id){ return "线程超时或异常 " + Thread.currentThread().getName(); public String Gloub_Test(){ return "走了全局的"; }
如上Service所示,加了@HystrixCommand的方法里,
如果没指定fallbackMethod 就会默认去找全局的defaultFallback
这里 当paymentInfo_ok 方法出错时,会调用Gloub_Test方法
当payment_Info_TimeOut出错时,会调用payment_Info_TimeOutHandler方法
***二.服务熔断***
1.熔断机制概述
熔断机制是应对雪崩效应的一种微服务链路保护机制,当扇出链路的某个微服务出错不可用或者响应时间太长,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的相应信息.当检测到该节点微服务调用相应正常后,恢复调用链路.
2.项目中使用
在上面的基础上,改写Service和Controller(添加以下代码)
//是否开启服务熔断(断路器) @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //服务请求的次数 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //时间的窗口期 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //当失败率达到多少后发生熔断 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), ******************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 不能为负:" + id; ************Controller******************** @GetMapping("/payment/circuit/{id}") String result = paymentService.PaymentCircuitBreaker(id); log.info(result + "***********"); return result;
如上所示,当访问paymentCircuitBreaker时,如果id小于零则会有一个运行错误,这时候就会通过服务降级来调用paymentCircuitBreaker_fallback方法,当错误的次数达到60%的时候(自己设的),就会出现服务熔断,这个时候再访问id大于零的情况,也会发生服务降级,因为开起了服务熔断,需要慢慢的恢复正常.
到此这篇关于SpringCloud之Hystrix的详细使用的文章就介绍到这了,更多相关SpringCloud Hystrix使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot使用Sharding-JDBC实现数据分片和读写分离的方法
本文主要介绍了SpringBoot使用Sharding-JDBC实现数据分片和读写分离,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-10-10
最新评论