spring boot 项目中使用Feign

1、如果你使有Maven或者gradle,先用引入Feign的jar包,这里用maven做例子:

<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.5.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.5.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>9.5.0</version>
</dependency>
2、在项目logback-spring.xml加入Feign日志配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE" />
<logger name="feign.Logger" level="debug" />(这一行是Feign日志配置,这样在项目中就可以优雅打印日志)
3、添加Feign configure日志
@Configuration
public class FeignConfig {
/**
* 启用Fegin自定义注解 如@RequestLine @Param
*/
@Bean
public Contract feignContract() {
return new Contract.Default();
}

@Bean
public HelloService fileConnect() {
return Feign.builder()
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.options(this.options())
.logger(new Slf4jLogger())
.logLevel(Level.FULL) (这里日志级别可以批定其他选项)
.retryer(new Retryer.Default(5000, 5000, 3))
.requestInterceptor(template -> template.header("Api-Token", "")
.header("Content-Type", "application/json"))
.target(HelloService.class, “http://project”); (这里的接口地址是举例说明,具体接口地址按自己项目中所用的)
}



/**
* connectTimeoutMillis=1000 链接超时时间
readTimeoutMillis=3500 响应超时时间,如果超过3.5秒没有接过发起下一次请求
*/
private Request.Options options() {
return new Request.Options(1000, 3500);
}
}
4、HelloService 
定义接口
public interface HelloService {

@RequestLine("POST /get/name")
Student getUserInfo(Map data);
}

实现类:
public class Student {
@Autowired
private HelloService helloservice;
 public Student getUserInfo(String userid){
	Map data=new LinkedHashMap(1);
data.put("userid", userId);
    Student student=helloservice.getUserInfo(data);
    System.out.println("学生信息为:"+new Gson().toJson(student));





 
posted @   一代天娇AS  阅读(1264)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示