Feign与Hystrix的搭配

2022-08-12 08:46:12

       分布式系统中,服务与服务之间的依赖错综复杂,一种不可避免的情况就是某个服务出现故障,导致依赖它的其他服务出现远程调度的线程阻塞,从而产生联动故障。Hystrix是Netflix公司的一个开源项目,它提供了一个熔断器功能,通过隔离服务的访问点阻止联动故障,并提供故障的解决方案,从而提高整个分布式系统的弹性。

之前我们看了eureka与feign实现负载均衡,hystrix的学习,继续在之前的负载均衡项目上做改造,以节省一些不必要的篇幅。

复制feign-consumer 为 feignhystrix-consumer,其他的feign工程不需要做改动。

按照惯例,第一步需要在pom.xml中因依赖,由于feign的起步依赖中,已经包含了hystrix的依赖,所以在hystrix中不需要再引依赖了。

改造步骤

1、 在application.properties 中增加熔断开关

默认的feign功能中,熔断开关是关闭的,所以,熔断器hystrix的开关需要手动打开

spring.application.name=eureka-client
eureka.client.service-url.defaultZone=http://localhost:5430/eureka/
server.port=5433
feign.hystrix.enabled=true

鼠标移到feign.hystrix.enabled上面时,会有弹窗提示 If true, an OpenFeign client will be wrapped with a Hystrix circuit breaker.

2、实现熔断回调接口

熔断回调接口需要继承远程调用接口HelloService,整个类用@Component组件修饰,将该类交给spring容器统一管理。

package com.example.consumer.hystrix;

import org.springframework.stereotype.Component;

import com.example.consumer.service.HelloService;

@Component
public class HiHystrix implements HelloService{

	@Override
	public String hello() {
		return "hi, sorry, service is not used.";
	}
}

3、远程接口配置熔断回调接口

package com.example.consumer.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.consumer.hystrix.HiHystrix;

/**
 * 远程调用接口
 * 调用远程服务eureka-server,并增加熔断方案HiHystrix
 * @author PC
 */
@FeignClient(value="eureka-server", fallback = HiHystrix.class)
public interface HelloService {

	@GetMapping("/hi")
	String hello();
}

至此,改造完成。

测试

启动feign-servicecenter服务注册中心,启动feign-provider、feign-provider2和feignhystrix-consumer

浏览器访问

http://localhost:5433/hello

可以看到两个服务提供实例依次提供服务

待关闭一个后,仅有的一个服务提供实例依然可以提供正常服务

待两个服务都关闭后,可以看到,客户端feignhystrix利用自身的回调接口向浏览器给出了反馈

待再次启动feign-provider服务后,访问时,可以再次请求到正常的远程服务

以上,使用hystrix的一点简单记录,供大家学习参考。谢谢

  • 作者:蜗牛-
  • 原文链接:https://blog.csdn.net/magi1201/article/details/85840281
    更新时间:2022-08-12 08:46:12