Loading

Rest实现服务熔断

(1)复制 shop_service_order 项目并命名为 shop_service_order_rest_hystrix

(2)配置依赖

在 shop_service_order_rest_hystrix 工程中添加Hystrix的相关依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

(3)开启熔断

在启动类 OrderApplication 中添加 @EnableCircuitBreaker 注解开启对熔断器的支持。
  @EntityScan("cn.itcast.entity")
  //@EnableCircuitBreaker //开启熔断器
  //@SpringBootApplication
@SpringCloudApplication
  public class OrderApplication {

      //创建RestTemplate对象
      @Bean
      @LoadBalanced
      public RestTemplate restTemplate() {
          return new RestTemplate();
      }


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


  }
可以看到,我们类上的注解越来越多,在微服务中,经常会引入上面的三个注解,于是Spring就提供了一个组合注解:@SpringCloudApplication

(4)配置熔断降级业务逻辑

@RestController
@RequestMapping("/order")
public class OrderController {

  @Autowired
  private RestTemplate restTemplate;


  //下订单
  @GetMapping("/product/{id}")
  @HystrixCommand(fallbackMethod = "orderFallBack")
  public Product findProduct(@PathVariable  Long id) {
      return restTemplate.getForObject("http://shop-service-
product/product/1", Product.class);
  }

  //降级方法
  public Product orderFallBack(Long id) {
      Product product = new Product();
      product.setId(-1l);
      product.setProductName("熔断:触发降级方法");
      return product;
  }
}
有代码可知,为 findProduct 方法编写一个回退方法fifindProductFallBack,该方法与 findProduct 方法具有相同的参数与返回值类型,该方法返回一个默认的错误信息。
在 Product 方法上,使用注解@HystrixCommand的fallbackMethod属性,指定熔断触发的降级方法是 findProductFallBack 。
  因为熔断的降级逻辑方法必须跟正常逻辑方法保证:相同的参数列表和返回值声明。
  在 findProduct 方法上 HystrixCommand(fallbackMethod = "findProductFallBack") 用来声明一个降级逻辑的方法
当 shop-service-product 微服务正常时,浏览器访问 http://localhost:9001/order/product/1

可以正常调用服务提供者获取数据。当将商品微服务停止时继续访问 
此时Hystrix配置已经生效进入熔断降级方法。

默认的Fallback

我们刚才把fallback写在了某个业务方法上,如果这样的方法很多,那岂不是要写很多。所以我们可以把Fallback配置加在类上,实现默认fallback: 

超时设置

在之前的案例中,请求在超过1秒后都会返回错误信息,这是因为Hystix的默认超时时长为1,我们可以通过配置修改这个值: 
  hystrix:
    command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMilliseconds: 2000

 

posted @ 2021-07-27 16:49  1640808365  阅读(154)  评论(0编辑  收藏  举报