Spring Cloud 熔断服务Hystrix

hystrix是一种保证服务稳定的组件,使服务不会因为某个服务崩溃导致整个应用崩溃。可以简单的理解为通用的异常处理。
hystrix用起来非常的简单,openfeign默认支持hystrix,只不过需要开启才行。

实战 

创建SpringBoot项目,引入Hystrix依赖:

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

在启动主类上添加如下代码:

@RestController
@EnableHystrix
@SpringBootApplication
public class HystrixDemoApplication {

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

	//通过HystrixCommand注解,手动指定一个降级方法,出现异常后会调用该降级方法
	@RequestMapping("/getName")
	@HystrixCommand(fallbackMethod = "getNameFallback")
	public String getName(String username) throws Exception{
		if(username.equals("zhuyu")){
			return "this is zhuyu";
		}else{
			throw new Exception();
		}
	}

	/**
	 * 出错后会调用该降级方法,返回指定的信息
	 * @param username
	 * @return
	 */
	public String getNameFallback(String username){
		return " this username is not exist ";
	}
}

运行程序,访问 http://localhost:8080/getName?username=zhuyu ,正常,没有触发降级

再访问 http://localhost:8080/getName?username=zhuyu11 ,可以看到返回了降级后设置的信息

好了,最简单的降级代码完成了。
上面仅演示了HystrixCommand的降级配置,还有很多其他配置,如:指定HystrixCommand的超时时间、线程池key以及线程池和队列大小,大家可以自行实验

HystrixCommand(fallbackMethod = "getNameFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000")
        }, 
        threadPoolKey = "hystrixDemoThreadPool",
        threadPoolProperties = {
                @HystrixProperty(name = "coreSize", value = "30"),
                @HystrixProperty(name = "maxQueueSize", value = "10")
        })

Hystrix不仅仅有熔断、降级,实际生产环境中 Hystrix 需要与网关和Feign集成,对服务间的调用做熔断、降级
还有Hystrix Dashborad仪表盘,用可视化的面板展示系统在一段时间内发生的请求情况

Hystrix还可以把多个请求合并进行一次性处理,可以减少网络通信与线程池资源,对处理高并发的业务效果较好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值