繼續上一篇,學習一下斷路器。
/**
* Created by liuyan9 on 2017/7/26.
*/
@FeignClient(value = "feign",fallback = CallBackFeign.class)
public interface CallFeignService {
@RequestMapping(value = "call", method = RequestMethod.GET)
String callFeign(@RequestParam(value = "name") String name);
}
在@FeignClient中增加屬性fallback,在調用接口的過程中,出現異常等情況,都會自動執行設置的對應類。
/**
* callback
*
* @author 劉研
* @create 2017-08-03 20:52
**/
@Component
public class CallBackFeign implements CallFeignService {
@Override
public String callFeign(String name) {
return "callback";
}
}
在被調用的服務中心,顯示的拋出異常。
/**
* Created by liuyan9 on 2017/7/26.
*/
@RestController
public class FeignController {
@Autowired
private HttpServletRequest request;
@RequestMapping(value = "/call", method = RequestMethod.GET)
public String home(@RequestParam String name) {
throw new NullPointerException();
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
@AliasFor("name")
String value() default "";
/** @deprecated */
@Deprecated
String serviceId() default "";
@AliasFor("value")
String name() default "";
String qualifier() default "";
String url() default "";
boolean decode404() default false;
Class<?>[] configuration() default {};
Class<?> fallback() default void.class;
Class<?> fallbackFactory() default void.class;
String path() default "";
boolean primary() default true;}
configuration表示了feign的配置,其對應默認實現類爲:FeignClientsConfiguration,這個類是一個配置類,裏面注入了很多的bean,包括:
Decoder,Encoder,Contrat,HystrixFeignConfiguration,feignRetry等等,我們也可以自定義這些bean的注入,只需要在@FeignClient中配置configuration屬性即可。
我們可以看到feign客戶端集成了Hystrix,所以feign直接可以設置斷路器。
fallback設置的類必須集成這個接口,並且要能被spring管理,即增加@Compoment註釋即可。
也可以使用fallbackFactory來提供錯誤信息。
未完待續。。。。