springCloud Hystrix 断路由

本文介绍如何使用Spring Cloud Hystrix实现服务间的熔断机制。具体步骤包括:1) 添加依赖;2) 编写配置文件,设置服务名称、端口等;3) 创建启动类并注入负载均衡RestTemplate;4) 编写控制器进行服务调用,并设置熔断方法。

第一步加入依赖:

  <dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-hystrix</artifactId>

    <version>1.2.6.RELEASE</version>

  </dependency>

第二步:编写配置文件application.properties

  spring.application.name=ribbon-hystrix
  server.port=8787
  eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
  eureka.instance.metadata-map.zone=beijing
  spring.cloud.loadbalancer.retry.enabled=true

  #hystrix.command.default.execution.timeout.enabled=false
  hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

第三步:编写启动类

import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringCloudApplication
public class EurekaClientRibbonHystrixApplication {

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

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

第四步:测试

  

@RestController
public class ConsumerController {
  @Autowired
  RestTemplate restTemplate;

  @Autowired
  DiscoveryClient client;

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  @HystrixCommand(fallbackMethod = "fallback" )
  public String add() throws InterruptedException {

    return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
  }

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

转载于:https://www.cnblogs.com/gslblog/p/7171100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值