spring-cloud-使用Hystrix实现断路器

必看提示以及声明:

请合理选择适合自己使用的方式,因个人原因产生的问题,均与博主无关

####介绍
在微服务架构中,服务被拆分成一个一个的单元,各个单元之间相互依赖调用。如果某个单元由于网络原因或者别的单元故障奔溃,那么会直接导致调用方对外的服务也发生延迟。若此时调用方的请求不断增加,最后就会出现因等待出现故障的依赖方响应而形成任务积压,最终导致自身服务的瘫痪,为了解决这个问题,我们可以采用断路器

在分布式架构中,当某个服务单元发生故障,使用断路器返回一个错误的相应,而不是进行长时间的等待,这样就不会使得线程被长时间占用,导致服务器的瘫痪。

Spring Cloud提供了Hystrix这么一个组件来实现断路器的功能。

大致流程

1:确认注册中心已启动

2:确认客户端已启动(上节是2222端口为服务端,我们可以创建并配置一模一样的端口号为2223的客户端)

3:开发工具创建maven项目(博主这里选择与客户端一样的创建流程,稍后修改下pom)

4:配置pom,并修改负载均衡的controller,创建service

图片暂无

准备

1:启动注册中心(博主这里端口号为:1111)以及2222端口2223端口的客户端

2:idea工具

具体流程

1:启动注册中心,访问http://localhost:1111,出现注册中心页面

2:启动客户端,访问http://localhost:1111,客户端已注册

3:修改Ribbon负载均衡项目的pom(博主这里是client-2333项目),添加如下依赖

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

4:修改Ribbon负载均衡项目的application中增加@EnableCircuitBreaker注解,表明使用断路器。

@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class RibbonApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

Hystrix使用消息队列的方式,如果连接的服务崩溃,则异步回调某个方法进行处理。

5: 新增一个Service类,在这个类中定义好如何访问,以及失败之后的返回等

代码如下

@Service
public class ComputeService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "addServiceFallback")
    public String addService() {
        return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
    }

    public String addServiceFallback() {
        return "error";
    }
}

这里重点是@HystrixCommand注解:表明该方法为hystrix包裹,可以对依赖服务进行隔离、降级、快速失败、快速重试等等hystrix相关功能

列举几个属性:

  1. fallbackMethod 降级方法

  2. commandProperties 普通配置属性,可以配置HystrixCommand对应属性,例如采用线程池还是信号量隔离、熔断器熔断规则等等

  3. ignoreExceptions 忽略的异常,默认HystrixBadRequestException不计入失败

  4. groupKey() 组名称,默认使用类名称

  5. commandKey 命令名称,默认使用方法名

5:在application.properties中配置如下:

spring.application.name=ribbon-consumer
server.port=2333
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

6:最后修改Controller
@RestController
public class ConsumerController {

    @Autowired
    private ComputeService computeService;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return computeService.addService();
    }
}

8:访问http://localhost:2333/add
当客户端关闭时访问: 显示error
客户端启动时访问: 返回正确的数据

碰到的问题以及解决方法

参考文章

https://blog.csdn.net/a60782885/article/details/69267934