五、Spring Cloud 的 Hystrix 组件

来源:互联网 发布:魔兽世界数据库 编辑:程序博客网 时间:2024/06/06 15:38

一、Maven 配置

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

二、主程序上配置的注解

@EnableHystrix或@EnableCiruitBreaker

三、Controller配置

        通过以下代码可以看出, 在/eureka/{id} 请求访问注解上,加了@HystrixCommand注解,如果访问失败,会请求findByIdFallback方法返回数据,在下文中,会详细描述Hystrix的更多功能。

       /** * #1 第一种   基于Eureka服务方式来调用  *  * @param id * @return */@GetMapping("/eureka/{id}")@HystrixCommand(fallbackMethod="findByIdFallback")public User findByIdEureka(@PathVariable Long id) {User user = this.restTemplate.getForObject("http://cloud-service/get/" + id, User.class);String rs = loadEurekaInstance();user.setEurekaServiceName(rs);return user;}public User findByIdFallback(Long id) {User user = new User();user.setId(-1L);user.setName("NULL");return user;}