feign 是netflix 提供的申明式的httpclient调用框架
整合方法
1.添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2.在application 添加注解
@EnableFeignClients
3.编写调用代码
@FeignClient(name = "jpaas-form") public interface FormClient { /** * 根据表单别名获取表单相关数据。 * @param alias * @param pk * @param initPermission * @return */ @GetMapping("/form/core/formPc/getByAlias") JsonResult<BpmView> getByAlias(@RequestParam(value = "alias") String alias, @RequestParam(value = "pk")String pk, @RequestParam(value = "initPermission") Boolean initPermission);
1.添加一个接口类。
2.增加@FeignClient 注解
name 指向需要调用的 微服务名称
3.增加调用方法
遵循 mvc的写法,如果返回的数据是一个java对象,最好把这个实体做成公共的类,供被调用者和调用者进行使用。
@GetMapping("/users/{id}")
UserDTO findById(@PathVariable Integer id);
方法示例,和spring mvc 差不多。
4.自定义FEIGN日志级别
feign 日志级别,就是需要打印feign的调用参数和响应数据。
使用java代码来实现。
1.编写配置类
import feign.Logger; import org.springframework.context.annotation.Bean; public class UserCenterFeignClientConfig { @Bean public Logger.Level level(){ return Logger.Level.FULL; } }
2.feign client 类指定配置
@FeignClient(name = "user-center", // fallback = UserCenterFeignClientFallback.class, // fallbackFactory = UserCenterFeignClientFallbackFactory.class, configuration = UserCenterFeignClientConfig.class ) public interface UserCenterFeignClient {
3.在日志中进行指定
编辑 application.yml
logging: level: com.demo.contentcenter.feignclient.UserCenterFeignClient: debug
注意这个日志界别需要为 debug 级别,只有在debug模式才会输出feign日志。
4. feign 多参数请求实现
请参考文章
http://www.imooc.com/article/289000
5.使用 feign 访问非 注册服务数据
有些情况下,我们使用feign 访问外部url,比如访问 博客网首页。
编写代码:
@FeignClient(name = "cnblogs", url = "https://www.cnblogs.com")
public interface ExternalFeignClient {
@GetMapping("/yg_zhang")
String index();
}
这里需要指定 name 和URL地址。
6.性能优化
配置启用http连接池:
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> <version>10.2.3</version> </dependency>
修改 application.yml
feign: client: config: # 全局配置 default: loggerLevel: basic httpclient: enabled: true max-connections: 200 max-connections-per-route: 50
7.feign 的常见问题
http://www.imooc.com/article/289005
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2019-04-05 springsecurity 源码解读 之 RememberMeAuthenticationFilter