springcloud-断路器Hystrix
Posted 小平1993
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud-断路器Hystrix相关的知识,希望对你有一定的参考价值。
前面博客已搭建出服务注册中心、服务提供者和服务消费者三个微服务,本文的案例我们依然在这三个案例的基础上来实现
一:搭建hystrx步骤
1.pom
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency>
2.消费者入口
添加@EnableCircuitBreaker
![技术分享图片](/img/jia.gif)
@EnableCircuitBreaker @SpringBootApplication @EnableDiscoveryClient public class RibbonConsumerApplication { public static void main(String[] args) { SpringApplication.run(RibbonConsumerApplication.class, args); } @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } }
3.Controller类
创建一个helloService来单独处理Controller的接口函数
![技术分享图片](/img/jia.gif)
@Service public class HelloService { @Autowired private RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "error") public String hello() { ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://HELLO-SERVICE/hello", String.class); return responseEntity.getBody(); } public String error() { return "error"; } }
![技术分享图片](/img/jia.gif)
@RestController public class ConsumerController { @Autowired private HelloService helloService; @RequestMapping(value = "/ribbon-consumer",method = RequestMethod.GET) public String helloController() { return helloService.hello(); } }
再运行后,访问这个消费者的方法,当其中一个生产者服务关掉时,连续刷新方法,也不会出现服务请求不到的情况,这就是我们想要的负载均衡效果!
是Hystrix断路器启动的效果
二:Hystrix缓存
在原来的helloService有注解@HystrixCommand在加一个注解@CacheResult,当参数都一样的时不调用请求直接返回缓存值,否则调用服务
@CacheResult,@CacheKey,@CacheRemove
![技术分享图片](/img/jia.gif)
@CacheResult(cacheKeyMethod = "getCacheKey2") @HystrixCommand public Book test6(Integer id) { return restTemplate.getForObject("http://HELLO-SERVICE/getbook5/{1}", Book.class, id); } public String getCacheKey2(Integer id) { return String.valueOf(id); }
![技术分享图片](/img/jia.gif)
@CacheResult @HystrixCommand public Book test6(@CacheKey Integer id,String aa) { return restTemplate.getForObject("http://HELLO-SERVICE/getbook5/{1}", Book.class, id); }
三:Hystrix请求合并(高并发请求这样的方案很棒)
高并发时通信次数增加会导致总的通信时间增加,线程池资源有限,高并发会有延迟,合拼请求能解决问题
原理:利用一个合并处理器,将对同一个服务发起的连续请求合并成一个请求进行处理(这些连续请求的时间窗默认为10ms)过程中涉及到的一个核心类就是HystrixCollapser
不怎么看懂,可以自行研究https://mp.weixin.qq.com/s/0QSKVLaDjBAscRaeccaXuA
以上是关于springcloud-断路器Hystrix的主要内容,如果未能解决你的问题,请参考以下文章
企业级 SpringCloud 教程 断路器(Hystrix)
企业级 SpringCloud 教程 断路器(Hystrix)