天天看点

SpringCloud - Hystrix(四)

spring:
  application:
    name: order
  cloud:
    config:
      discovery:
        enabled: true
        service-id: CONFIG
      profile: test
    stream:
      bindings:
        myMessage:
          group: order
          content-type: application/json
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 1000
    getProductInfoList:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000      
package com.imooc.order.controller;
 
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
 
@RestController
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
 
  @HystrixCommand
  @GetMapping("/getProductInfoList")
  public String getProductInfoList(@RequestParam("number") Integer number) {
    if (number % 2 == 0) {
      return "success";
    }

    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.postForObject("http://127.0.0.1:8005/product/listForOrder",
        Arrays.asList("157875196366160022"),
        String.class);
  }
 
  private String defaultFallback() {
    return "默认提示:太拥挤了, 请稍后再试~~";
  }
}      
  • 在配置中配置服务降级时,一定要在方法上加上@HystrixCommand注解,默认是对应的方法名。

继续阅读