spring cloud hystrix 服务容错保护

代码例子下载:https://download.csdn.net/download/spark_guo/10501108

在微服务架构中存在那么多的服务单位。若一个单元出现故障就很容易因依赖关系而引发故障的蔓延,最终导致整个系统的瘫痪,这样的架构相较传统架构更加不稳定。为了解决这样的问题,产生了断路器等一系列的服务保护机制。


在分布式架构中,断路器模式的作用也是类似的,当某个服务单元发生故障之后通过断路器的故障监控,类似熔断保险丝向调用方返回一个错误响应,而不是长时间的等待,这样就不会使得线程因调用故障服务才会长时间占用不释放,避免故障在分布式系统中的蔓延。

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

搭建测试例子:

1、pom.xml引入

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

2、客户端,主要启动类上加上@EnableCircuitBreaker注解,开启断路器功能;

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerApplication 
{
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}

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

}

3、在服务方法上加上@HystrixCommand(fallbackMethod="helloFallback")注解,指定回调方法。

@Service
public class HelloService {
@Autowired
RestTemplate restTemplate; 

@HystrixCommand(fallbackMethod="helloFallback")
public String helloService(){
long start = System.currentTimeMillis();
String result = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class).getBody();
System.out.println("cost:"+(System.currentTimeMillis() -start));
return result;
}

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

}

4、服务端测试:

@RestController
public class HelloController 
{
private final Logger logger = Logger.getLogger(getClass());

@Autowired
private DiscoveryClient client;

@RequestMapping(value="/hello", method = RequestMethod.GET)
    public String index() throws Exception
    {
ServiceInstance serviceInstance = client.getLocalServiceInstance();

// 让处理线程等待几秒钟
int sleepTime = new Random().nextInt(3000);
logger.info("sleepTime:"+sleepTime);
Thread.sleep(sleepTime);

logger.info("/hello, host:" + serviceInstance.getHost() +", service_id:"+serviceInstance.getServiceId());
String result = "Hello World!";
                System.out.println(result);
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值