3 spring cloud hystrix学习

本文介绍如何使用SpringCloud Hystrix实现服务间的断路器功能,通过实例演示当服务出现故障时,如何避免线程长时间等待,确保系统稳定性。包括配置Eureka服务、Provider服务及Hystrix服务,以及代码实现和服务注册流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Cloud Hystrix

定义:当线程调用服务时,因为服务的故障而出现长时间的等待的情况时,hystrix会返回一个错误响应,防止该线程长时间挂起而影响其他线程的性能。我们将之称为断路器。

1 快速开始

首先启动一个Eureka服务,端口为7001,服务名叫做sb-eureka

然后启动两个provider服务,端口为7011和7021,服务名都叫做sb-provider,都注册到sb-eureka服务注册中心上,两个服务的controller都有Provider.getName()方法,且一个返回“张三”,一个返回“李四”。

最后编写hystrix服务,端口为7041,服务名叫做sb-hystrix,也注册到sb-eureka服务注册中心上。通过RestTemplate启动了默认的线性轮询均衡负载。

接下俩详细看一下hystrix的代码,另外两部分代码请自行编写。

配置文件application.yml;

spring:
  application:
    name: sb-hystrix
server:
  port: 7041

eureka:
  client:
    register-with-eureka: true
    service-url:
      defaultZone: http://root:root@localhost:7001/eureka


pom文件:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!--Hystrix依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
    </dependencies>

入口启动类:HystrixApplication;

@SpringBootApplication
@EnableEurekaClient
/*注释开启断路器功能*/
@EnableCircuitBreaker
public class HystrixApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    public static void main(String[] args) {
        SpringApplication.run(HystrixApplication.class, args);
    }
}


Controller类HystrixController;

@RestController
@RequestMapping("Hystrix")
public class HystrixContreoller {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("getName")
    //该注解指定断路器返回的错误响应方法为errorBack()
    @HystrixCommand(fallbackMethod = "errorBack")
    public Object hystixController(){
        return restTemplate.getForObject("http://sb-provider/Provider/getName",String.class);
    }

    String errorBack(){
        return "服务器挂啦";
    }
}

此时进入localhost:7001的注册中心界面,可以看到此时有两个sb-providre和一个sb-hystrix服务已经注册到该注册中心上。

当我们访问localhost:7041/Hystrix/getName时,会依次返回“张三”和“李四”。

此时的sb-provider服务都健壮的运行着,无法触发断路器。

现在我们将sb-provider中的一个服务关闭,依然访问localhost:7041/Hystrix/getName时,就会经常返回“服务器挂啦”,说明此时的断路器起作用了。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值