跟我學Spring Cloud(Finchley版)-14-Feign使用Hystrix

Feign默認已經整合了Hystrix,本節詳細探討Feign使用Hystrix的具體細節。git

服務降級

  • 加配置,默認Feign是不啓用Hystrix的,須要添加以下配置啓用Hystrix,這樣全部的Feign Client都會受到Hystrix保護!github

    feign:
      hystrix:
        enabled: true
  • 提供Fallback:spring

    @FeignClient(name = "microservice-provider-user", fallback = UserFeignClientFallback.class)
    public interface UserFeignClient {
      @GetMapping("/users/{id}")
      User findById(@PathVariable("id") Long id);
    }
    
    @Component
    class UserFeignClientFallback implements UserFeignClient {
      @Override
      public User findById(Long id) {
        return new User(id, "默認用戶", "默認用戶", 0, new BigDecimal(1));
      }
    }

得到形成fallback的緣由

@FeignClient(name = "microservice-provider-user", fallbackFactory = UserFeignClientFallbackFactory.class)
public interface UserFeignClient {
  @GetMapping("/users/{id}")
  User findById(@PathVariable("id") Long id);
}

@Component
@Slf4j
class UserFeignClientFallbackFactory implements FallbackFactory<UserFeignClient> {
  @Override
  public UserFeignClient create(Throwable throwable) {
    return new UserFeignClient() {
      @Override
      public User findById(Long id) {
        log.error("進入回退邏輯", throwable);
        return new User(id, "默認用戶", "默認用戶", 0, new BigDecimal(1));
      }
    };
  }
}

Feign啓用/禁用Hystrix

全局啓用

feign.hystrix.enabled: true

全局禁用

feign.hystrix.enabled: false

或直接省略不寫。app

局部啓用

利用Feign配置的自定義,爲指定Feign Client指定以下配置類便可,Feign配置自定義詳見:跟我學Spring Cloud(Finchley版)-10-Feign深刻ide

public class FeignDisableHystrixConfiguration {
    @Bean
	@Scope("prototype")
	public HystrixFeign.Builder feignBuilder() {
		return HystrixFeign.builder();
	}
}

局部禁用

public class FeignDisableHystrixConfiguration {
    @Bean
	@Scope("prototype")
	public Feign.Builder feignBuilder() {
		return Feign.builder();
	}
}

配套代碼

服務降級:ui

得到形成fallback的緣由:prototype

本文首發

http://www.itmuch.com/spring-cloud/finchley-14/code

乾貨分享

全是乾貨

相關文章
相關標籤/搜索