当前位置:网站首页>Feign application and source code analysis
Feign application and source code analysis
2022-08-08 09:30:00 【Devil's Resurrection】
Feign是Netflix开发的声明式、模板化的HTTP客户端,Feign可帮助我们更加便捷、优雅地调用HTTP API.Feign可以做到使用 HTTP 请求远程服务时就像调用本地方法一样的体验,开发者完全感知不到这是远程方法,更感知不到这是个 HTTP 请求.
The following examples are all taken from the official website source code
简单应用
服务端代码,简单定义一个restful风格的接口,启动spring boot应用:
@EnableDiscoveryClient
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
@RestController
class EchoController {
@GetMapping("/echo/{string}")
public String echo(@PathVariable String string) {
System.out.println("hello Nacos Discovery " + string);
return "hello Nacos Discovery " + string;
}
}
}
客户端源代码:
@SpringBootApplication
@EnableDiscoveryClient(autoRegister = true)
@EnableFeignClients
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class,
configuration = FeignConfiguration.class)
public interface EchoService {
@GetMapping("/echo/{str}")
String echo(@PathVariable("str") String str);
}
}
class FeignConfiguration {
@Bean
public EchoServiceFallback echoServiceFallback() {
return new EchoServiceFallback();
}
}
class EchoServiceFallback implements EchoService {
@Override
public String echo(@PathVariable("str") String str) {
return "echo fallback";
}
}
客户端定义了Feignrelated core interfaces: EchoService接口类,There is no concrete implementation class for this interface,This interface can be understood asMybatis的Mapper接口,The final call to the interface method is actually the proxy class that calls this interface,made a call to the server,另外springIn parsing this interface is also followedMybatisusing the same technique,通过FactoryBean.getObject()调用FeignInvocationHandler生成代理对象注册到spring容器.EchoService的注解@FeignClientDefines the application name of the service,and measures to degrade services.
@RestController
public class TestController {
@Autowired
private EchoService echoService;
@GetMapping("/echo-feign/{str}")
public String feign(@PathVariable String str) {
return echoService.echo(str);
}
}
最后定义一个restfulThe interface provides the call junction to the outside world,通过spring的@Autowired注入EchoService代理对象,在方法体内调用echoService.echo()method will be sent to the serverrestful调用.
这样一个完整的Feign调用就完成了:
Feignrelated extension mechanism
Feign日志配置
在application.properties中设置FeignThe log level of the package path where it is located is Debug,Only this followsFeign配置才能生效:
logging.level.com.alibaba.cloud.examples=debug
在Feign使用中的FeignConfiguration中注册Bean
/**
* 日志级别
* NONE【性能最佳,适用于生产】:不记录任何日志(默认值).
* BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及执行时间.
* HEADERS:记录BASIC级别的基础上,记录请求和响应的header.
* FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body和元数据.
* @return
*/
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
配置为FULL结果:
配置为BASIC:
作用:Help programmers to view call information when developing.
额外的,We can also take effect globally by defining a configuration class,The above is only a partial definitionEchoService接口.
@Configuration
public class FeignConfig {
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
FeignInterceptors implement parameter passing
定义FeignAuthRequestInterceptor类,并实现RequestInterceptor接口的apply()方法,向RequestTemplate中设置tokenTo realize the authentication of downstream services.
public class FeignAuthRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
// 业务逻辑
String access_token = UUID.randomUUID().toString();
template.header("Authorization",access_token);
}
}
并在FeignConfiguration中定义Bean
/**
* 自定义拦截器
* @return
*/
@Bean
public FeignAuthRequestInterceptor feignAuthRequestInterceptor(){
return new FeignAuthRequestInterceptor();
}
另外,FeignProvides us with a basic authentication classBasicAuthRequestInterceptor,This can be defined directly in the configuration classBean,
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("rick", "123456");
}
测试:You can see that a request header is added to the requestkay-value对.
超时时间配置
The timeout includes request connection timeout and request read(处理)数据超时时间,直接在application.properties中配置
#请求连接超时时间,默认2s
feign.client.config.service-provider.connect-timeout=3000
#请求读取数据超时时间,默认5s
feign.client.config.service-provider.read-timeout=6000
将service-providermid service sleep7s,发起调用后
@GetMapping("/echo/{string}")
public String echo(@PathVariable String string) {
System.out.println("hello Nacos Discovery " + string);
try {
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello Nacos Discovery " + string;
}
look look...Read timed out 了.
Client component extension
FeignThe default is to use after the call is madeJDK的HttpURLConnection发起http请求:
通过引入Apache httpclient The component can replace the default onejdk的HttpURLConnection
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.7</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>10.1.0</version>
</dependency>
Of course others can be introducedhttp client组件:如
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
GZIP压缩
使用GZIPThe compression function is to compress the sent data,提高网络传输效率,By configuring on the client side
feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048
feign.compression.response.enabled=true
Initiate call result:
注意:GZIP不支持okhttp,At parsing time only does not existokhttp3,配置才会生效
引入okhttp3,并配置使用okhttp3 发起http请求:
feign.httpclient.enabled=false
feign.okhttp.enabled=true
当使用okhttp3时测试结果:没有使用GZIP压缩
编解码器
配置编解码器,Do not use the default codec,使用配置的:
@Bean
public Decoder decoder() {
return new JacksonDecoder();
}
@Bean
public Encoder encoder() {
return new JacksonEncoder();
}
Feign源码解析
Feign使用FactoryBean技术将FeignThe proxy object generated by the interface is registered tospring容器,
未完待续...
边栏推荐
- 【无标题】
- COMSOL Multiphysics 6.0软件安装包和安装教程
- 【图像分类】2022-MaxViT ECCV
- 【office】word
- VPP静态映射实现DNAT
- 入职半个月的一些思考
- Android Studio关于MainActivity中的“import kotlinx.android.synthetic.main.activity_main.*”出现错误提示
- Golang实现sha256或sha512加密
- 移动端/嵌入式-CV模型-2019:MobelNets-v3
- Raspberry pie 】 【 without WIFI even under the condition of the computer screen
猜你喜欢
随机推荐
VPP静态映射实现DNAT
LAN技术-5Eth-Trunk
文献学习(part33)--Clustering by fast search and find of density peaks
【收藏】3. 壁纸收藏
LeetCode:第305场周赛【总结】
交换两个整型变量的三种方法
The keys of the Flutter storage database
shell脚本知识记录
移动端/嵌入式-CV模型-2018:MobelNets-v2
22-08-06 Xi'an EasyExcel implements dictionary table import and export
数学基础(一)矩阵对角化、SVD分解以及应用
nodeJs--egg框架介绍
oracle中联表相关思考
DVWA full level detailed customs clearance tutorial
Implementation principle of priority queue
各位大佬想问下, flinkcdc采集oracle我看了下延迟大概两分钟左右,想问下有啥解决方法吗
To make people's consumption safer, more assured and more satisfied
HyperLynx(三)传输线类型及相关设置
Offensive and defensive world - ics-05
Excel中text函数5中常用方法