Spring Cloud 微服务四:熔断器Spring cloud hystrix

2022-10-23,,,

前言:在微服务架构中,一般都是进程间通信,有可能调用链都比较长,当有底层某服务出现问题时,比如宕机,会导致调用方的服务失败,这样就会发生一连串的反映,造成系统资源被阻塞,最终可能造成雪崩。在spring cloud家族中,hystrix就是用来处理这个问题的,本章将重点介绍该组件。前情回顾请参考:

Spring Cloud 微服务一:Consul注册中心

Spring Cloud 微服务二:API网关spring cloud zuul

Spring Cloud 微服务三: API网关Spring cloud gateway

hystrix概览

Spring Cloud Hystrix 实现了断路器、线路隔离等一系列服务保护功能。它也是基于 Netflix 的开源框架 Hystrix 实现的,该框架的目标在于通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix 具备服务降级、服务熔断、线程和信号隔离、请求缓存、请求合并以及服务监控等强大功能

hytrix集成和配置
准备工作,为了使用feign以及hystrix需要对之前的代码做少许调整,否则可能会出现无法负载的问题。

首先是user-api,需要把pom中的依赖全部删除,保持api的简洁性;另外删除UserService接口中的所有注解,后面会把注解放到实现类中,这样也保持了接口的整洁性。

public interface UserService {

    List<User> getAllUsers();
}

        然后是user-service,将注解放到实现类中

@RestController
public class UserServiceImpl implements UserService { @GetMapping("/all")
@Override
public List<User> getAllUsers() {
List<User> userList = new ArrayList<User>(); // should call DAO methods
userList.add(new User(1,"Dalston"));
userList.add(new User(2,"Edgware"));
userList.add(new User(3, "Finchley")); return userList;
}
}

最后,user-consumer做相应的修改,修改UserServiceClient接口,去掉对UserService的继承,这也是spring官方提倡的做法,同时在@FeignClient注解中添加fallback类,该类用于服务出故障时调用的本地方法

@FeignClient(name = "user-service", fallback = UserServiceClientFallback.class)
public interface UserServiceClient {
@GetMapping("/all")
List<User> getAllUsers();
}

添加UserServiceClientFallback类,实现具体方法

@Component
public class UserServiceClientFallback implements UserServiceClient {
@Override
public List<User> getAllUsers() {
System.out.println("Fallback service");
List<User> errorList = new ArrayList<>();
errorList.add(new User(2001,"get fallback"));
return errorList;
}
}

这样,对于原有服务的修改就完成了

启动熔断,在user-consumer的启动类中添加@EnableCircuitBreaker注解,用于启用hystrix

@EnableCircuitBreaker
@SpringBootApplication
@EnableFeignClients({"com.boe.micro.service"})
public class UserConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserConsumerApplication.class, args);
}
}

调整配置文件,启用hystrix,配置文件中追加如下配置 

feign:
hystrix:
enabled: true

测试,启动user-consumer,user-service,访问http://localhost:10080/users,会返回正常结果,停掉user-service,再访问该地址,会调用UserServiceClientFallback中的方法

Spring Cloud 微服务四:熔断器Spring cloud hystrix的相关教程结束。

《Spring Cloud 微服务四:熔断器Spring cloud hystrix.doc》

下载本文的Word格式文档,以方便收藏与打印。