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));
 
 
 
 
 
 
 
 
 
 
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM