OpenFeign讲解+面试题
一:OpenFeign是什么?
是一个声明式的web客户端,只需要创建一个接口,添加注解即可完成微服务之间的调用
二:调用微服务的方式?
- ribbon +restTemplate方式调用
- openFeign通过接口+注解的方式调用
三:如何使用OpenFeign?
- pom文件添加依赖
- yaml配置文件
- 主启动类,标注@EnableFeignClients注解
- 编写调用接口并标注@FeignClient注解
- 接口中的方法为实际想要调用的服务的方法
四:OpenFeign超时机制
因为OpenFeign的底层是ribbon进行负载均衡,所以它的超时时间是由ribbon控制
五:底层核心原理
底层通过JDK动态代理获取到接口中的服务信息,使用Ribbon管理后的RestTemplate进行调用
@SpringBootTest
class ApplicationTests {@Autowiredprivate RestTemplate restTemplate;@Testvoid contextLoads() {UserOrderFeign o = (UserOrderFeign) Proxy.newProxyInstance(UserOrderFeign.class.getClassLoader(), new Class[]{UserOrderFeign.class}, new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 获取目标方法上的注解GetMapping MethodAnnotation = method.getAnnotation(GetMapping.class);// 获取注解上的请求路径String path = MethodAnnotation.value()[0];// 获取目标方法所在的类Class<?> aClass = method.getDeclaringClass();// 获取类上面的注解FeignClient classAnnotation = aClass.getAnnotation(FeignClient.class);// 获取注解上的value值(服务名)String applicationName = classAnnotation.value();// 拼接URLString url = "http://"+applicationName+"/"+path;// 使用Ribbon托管后的RestTemplate进行调用return restTemplate.getForObject(url, String.class);}});String s = o.doOrder();System.out.println(s);}
}
六:面试题
- Feign和openFeign有什么区别?
OpenFeign讲解+面试题
一:OpenFeign是什么?
是一个声明式的web客户端,只需要创建一个接口,添加注解即可完成微服务之间的调用
二:调用微服务的方式?
- ribbon +restTemplate方式调用
- openFeign通过接口+注解的方式调用
三:如何使用OpenFeign?
- pom文件添加依赖
- yaml配置文件
- 主启动类,标注@EnableFeignClients注解
- 编写调用接口并标注@FeignClient注解
- 接口中的方法为实际想要调用的服务的方法
四:OpenFeign超时机制
因为OpenFeign的底层是ribbon进行负载均衡,所以它的超时时间是由ribbon控制
五:底层核心原理
底层通过JDK动态代理获取到接口中的服务信息,使用Ribbon管理后的RestTemplate进行调用
@SpringBootTest
class ApplicationTests {@Autowiredprivate RestTemplate restTemplate;@Testvoid contextLoads() {UserOrderFeign o = (UserOrderFeign) Proxy.newProxyInstance(UserOrderFeign.class.getClassLoader(), new Class[]{UserOrderFeign.class}, new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 获取目标方法上的注解GetMapping MethodAnnotation = method.getAnnotation(GetMapping.class);// 获取注解上的请求路径String path = MethodAnnotation.value()[0];// 获取目标方法所在的类Class<?> aClass = method.getDeclaringClass();// 获取类上面的注解FeignClient classAnnotation = aClass.getAnnotation(FeignClient.class);// 获取注解上的value值(服务名)String applicationName = classAnnotation.value();// 拼接URLString url = "http://"+applicationName+"/"+path;// 使用Ribbon托管后的RestTemplate进行调用return restTemplate.getForObject(url, String.class);}});String s = o.doOrder();System.out.println(s);}
}
六:面试题
- Feign和openFeign有什么区别?