openFeign是SpringCloud体系下进行服务调用的框架,他是一款声明式的REST服务调用框架。
一、openFeign的配置和使用
使用openFeign需要引入依赖spring-cloud-starter-openfeign,本文以nacos作为注册中心,需要引入spring-cloud-starter-alibaba-nacos-discovery依赖。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
properties中配置项:
#feign start
feign.client.config.feignName.connectTimeout=5000
feign.client.config.feignName.readTimeout=5000
#日志级别
feign.client.config.feignName.loggerLevel=full
启动类上的配置,需要加上@EnableFeignClients
注解。
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class SpringCloudStarterOpenfeignExamplesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudStarterOpenfeignExamplesApplication.class, args);
}
}
服务提供方的只需要按照常规的@RestController进行编写:
@RestController
public class LeafController {
@RequestMapping(value = "/api/segment/get/{key}")
public String getSegmentId(@PathVariable("key") String key) {
return get(key, segmentService.getId(key));
}
}
服务调用方的配置,需要加上openFeign的注解@FeignClient
,去value值即为需要远程调用的服务名。
@FeignClient("yangnkMall-uniqID")
public interface UniqIdApi {
@RequestMapping(value = "/api/segment/get/{key}")
String getSegmentId(@PathVariable("key") String key);
}
二、openFeign的自定义拓展
1、通过Ribbon自定义负载均衡
openFeign集成了Ribbon,默认支持Ribbon进行负责均衡,直接在properties文件中加上对应参数即可。
#Ribbon start
#请求时间5秒
ribbon.ReadTimeout=5000
#连接时间5秒
ribbon.ConnectTimeout=5000
同时可以自定义负载均衡策略:
@Slf4j
@Configuration
public class MyRibbonConfig {
@Bean
public IRule myRule(){
return new RandomRule();//定义为随机,默认是轮询
}
2、自定义HttpClient
openFeign的默认的http调用方式是JDK原生HttpURLConnection,缺乏线程池和自定义调用参数等设置。可以选择第三方客户端HttpClient,如果需要使用HttpClient做服务调用的客户端,需要引入Httpclient依赖。
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
properties中配置项:
# 开启HttpClient
feign.httpclient.enabled=true
# 使用HttpClient 5(Apache HttpClient 5)
feign.httpclient.hc5.enabled=false
# 禁用OkHttp
feign.okhttp.enabled=false
三、原理
四、实现
代码实现:https://github.com/yangnk/yangnkMall/tree/master/Order/src/main/java/com/yangnk/order/myTest
TODO
- 充实文章中各章节;
- 补充原理实现;
参考资料
- Spring Cloud openFeign官方文档:https://docs.spring.io/spring-cloud-openFeign/docs/2.2.7.RELEASE/reference/html/
- Github源码:https://github.com/openFeign/feign
- 『openFeign』使用与配置篇:https://juejin.cn/post/7130041310177820685#heading-12
- 详细讲解openFeign的使用姿势!:https://developer.aliyun.com/article/775626#slide-0 (简单易懂,可以首先参考这篇文章)
- 服务调用Ribbon、openFeign:https://juejin.cn/post/6992119925519155207#heading-18 (openFeign和Ribbon结合的文章)
- OpenFeign 简单使用:https://blog.csdn.net/qq_41538097/article/details/124112466 (其中解释了OpenFeign的原理)
- 代码参考:https://github.com/yehongzhi/example/blob/main/consumer/src/main/resources/application.yml