继续上一篇,学习一下断路器。
/**
* 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();
}
}
断路器比较简单理解,继续学习一下feign客户端的源码实现。
@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来提供错误信息。
未完待续。。。。