在ribbon使用断路器

改造serice-ribbon 工程的代码,首先在pox.xml文件中加入spring-cloud-starter-hystrix的起步依赖:

引入

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

在程序的启动类ServiceRibbonApplication 加@EnableHystrix注解开启Hystrix:

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class ServiceRibbonApplication {

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

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

}

改造HelloService类,在hiService方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为”hi,”+name+”,sorry,error!”,代码如下:

@Service
public class HelloService {

@Autowired
RestTemplate restTemplate;

@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
}

public String hiError(String name) {
return "hi,"+name+",sorry,error!";
}
}

启动:service-ribbon 工程,当我们访问http://localhost:8764/hi?name=forezp,浏览器显示:

hi forezp,i am from port:8762

此时关闭 service-hi 工程,当我们再访问http://localhost:8764/hi?name=forezp,浏览器会显示:

hi ,forezp,orry,error!

这就说明当 service-hi 工程不可用的时候,service-ribbon调用 service-hi的API接口时,会执行快速失败,直接返回一组字符串,而不是等待响应超时,这很好的控制了容器的线程阻塞。

最新文章

  1. android Intent的常用flags
  2. oracle for loop循环以及游标循环
  3. BZOJ4310 : 跳蚤
  4. 有图有真相——关于“视频专辑:零基础学习C语言 ”
  5. malloc、calloc、realloc的区别
  6. 阅读《RobHess的SIFT源码分析:综述》笔记2
  7. 由点击页面其它地方隐藏div所想到的jQuery的delegate
  8. 2016年如果还没有关注这些机器人公司,你就out了
  9. Linux里面怎样修改主机名
  10. mac os 中如何修改顶栏图标的顺序
  11. Flutter获取屏幕宽高和Widget大小
  12. Java利用cors实现跨域请求
  13. 出题人的RP值(牛客练习赛38--A题)(排序)
  14. Ubuntu pkg_resources.DistributionNotFound: The &#39;Scrapy==1.0.3&#39; distribution was not found and is required by the application
  15. hdu 4339 Query(两种思路求解)
  16. ArcGIS Runtime SDK for iOS之符号和渲染
  17. Python str list to list
  18. Python基础-画图:matplotlib.pyplot.scatter
  19. 非极大值抑制(NMS,Non-Maximum Suppression)的原理与代码详解
  20. JavaScript函数的多种定义方法

热门文章

  1. 安装包设计-------安装(QT)---------知识总结
  2. chrome出现“由贵单位管理”原因及解决方法
  3. MySQL中使用LIMIT分页
  4. Ubuntu 在VirtualBox里无法联网【已解决】
  5. sql注入笔记-sqlite
  6. ajax与HTML5 history API实现无刷新跳转
  7. 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_14-异常处理-异常处理的问题分析
  8. clientdataset的使用
  9. [Graphics] UIColor created with component values far outside the expected range, Set a breakpoint on UIColorBreakForOutOfRangeColorComponents to debug. This message will only be logged once.
  10. DELL服务器管理工具和RACADM介绍