Feign
feign 日志
- 配置 yaml
logging:
level:
***.***: DEBUG
日志级别:NONE ,BASIC,HEADERS,FULL
- 添加bean
@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
日常使用中建议使用basic 或者none
- 日志会影响性能
- 亲身体验:部分请求responseBody信息过于庞大会影响其他日志的查看,使用full,headers 完全没有意义
feign 优化
feign 底层实现默认是urlConnection ,是不支持连接池的。一次http请求建立连接会三次握手,断开连接四次挥手,不适用连接池性能比较差
可以使用httpClient 或者 OKHttp
pom中添加依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
httpclient有版本不一致问题,可能需要指定版本
yaml中配置
feign:
client:
config:
userservice: debug
httpclient:
enabled: true
max-connections: 200 # 最大连接数
max-connections-per-route: 50 #每个请求的最大连接数
最大连接数和每个请求最大连接数需要根据实际的压测结果来决定
feign的使用记录
在请求api包内 不要再接口上使用requestMapping 注解
- 使用了注解会使其他服务提供的接口会背当前应用扫描到,可以直接请求调用,
- 会影响fallback的定义
feign自定义异常
@Configuration
public class FeignClientErrorDecoder extends ErrorDecoder.Default {
private Logger logger = LoggerFactory.getLogger(FeignClientErrorDecoder.class);
@Override
public Exception decode(String methodKey, Response response) {
Exception exception = super.decode(methodKey, response);
try {
// 如果是FeignException,则对其进行处理,并抛出BusinessException
if (exception instanceof FeignException && ((FeignException) exception).responseBody().isPresent()) {
ByteBuffer responseBody = ((FeignException) exception).responseBody().get();
String bodyText = StandardCharsets.UTF_8.newDecoder().decode(responseBody.asReadOnlyBuffer()).toString();
FeignErrorVo errorResponseVo = JSONObject.parseObject(bodyText, FeignErrorVo.class);
logger.error("{}错误码{}信息为: {} ",response.request().url(),errorResponseVo.getStatus() ,errorResponseVo.getMessage());
return new BusinessException("服务出现异常,请稍后再试");
}
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
return exception;
}
}
其中 FeignErrorVo 和 BusinessException 可以自行根据业务来决定
Feign 超时配置:
openfeign-starter 中自带了hystrix,可以不用添加hystrix starter
# ribbon:
# ReadTimeout: 5000
# ConnectTimeout: 5000
# feign 客户端超时配置
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
# hystrix 超时配置
hystrix:
enabled: true
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 180000
spring:
cloud:
config: # 相同配置下优先使用本地配置 (注:需在nacos上配置才生效!)
override-none: true
allow-override: true
override-system-properties: false
hystrix 不是使用自动装配,添加到yaml 中可能idea 会不识别。feign 执行调用时会进行添加配置
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律