Spring cloud Hystrix 服务容错保护---断路器(1)

本文介绍了在微服务架构中使用断路器模式的重要性,以防止因单个服务故障引发的连锁反应。通过Spring Cloud提供的Hystrix组件实现断路器功能,并展示了具体的配置与代码示例。

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

在微服务架构中,存在着那么多服务单元,而且单元与单元之间存在着很多调用,万一某一个服务单元出现问题,就很有可能因为依赖关系而引发故障的蔓延,最终导致整个系统瘫痪,所以我们需要断路器。

在分布式架构中,断路器模式也是一样的,当某个服务单元发生故障,通过断路器的故障监控,向调用方返回一个错误响应,而不是长时间等待。这样就避免了雪崩式的连环故障导致系统瘫痪。

快速入门:

导入依赖:

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

application类:

@SpringCloudApplication
@RibbonClients(defaultConfiguration = RibbonRuleConfiguration.class)
public class RibbonApplication {

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

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

@SpringCloudApplication注解包含了:

@Target({ ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTI ) 
@Documented
@Inherited
@SpringBootApplication 
@EnableDiscoveryClient 
@EnableCircuitBreaker
publicInterface SpringCloudApplication {

}

包含了Spring cloud标准的服务发现和断路器,@EnableCricuitBreaker就代表了断路器。

改造服务消费方式:

@Service
public class HelloService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "fallBack")
    public String helloService(){
        return restTemplate.getForObject("http://HELLOSERVICE-1/hello",String.class);
    }


    public String fallBack(){
        return "error";
    }
}
@RestController
public class ConsumerController {

    @Autowired
    private HelloService helloService;
    @RequestMapping(value = "/consumer")
    public String getvalue(){

        return helloService.helloService();
    }
}

现在把服务提供者停掉,然后访问consumer接口,返回的是error

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值