Netflix开源的声明式HTTP客户端,Feign GitHub地址
1、集成Feign
加依赖 <!-- feign 声明式HTTP客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>加注解
写配置:无
2、写代码:
新建UserCenterFeignClient客户端类 package com.hzb2i.contentcenter.FeignClient; import com.hzb2i.contentcenter.domain.dto.user.UserDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(name = "user-center") public interface UserCenterFeignClient { /** * http://user-center/users/{id} * @param id * @return */ @GetMapping("/users/{id}") UserDto findById(@PathVariable Integer id); } 重构调用:用于理解feign设计、分析源码
1、指定日志级别
PS:springBoot日志配置 PS:feign日志级别
java代码配置① 新建UserCenterFeignConfiguration配置
package com.hzb2i.contentcenter.configuration; import feign.Logger; import org.springframework.context.annotation.Bean; public class UserCenterFeignConfiguration { @Bean public Logger.Level level(){ return Logger.Level.FULL; } }② feign客户端类引入配置 ③ feign是建立在客户端类接口debug基础上,需要配置文件中加入全路径
logging: level: com.hzb2i.contentcenter.feignClient.UserCenterFeignClient: debugPS:如果feign配置类UserCenterFeignConfiguration加了@Configuration注解,就需要将该类移到启动类MapperScan能否扫描的包以外(父子上下文重复扫描)
配置属性配置 全局配置-代码方式 在启动类进行配置 全局配置-配置属性配置 PS:feign支持的配置项 小结: 优先级:全局代码<全局属性<细粒度代码<细粒度属性由于用户中心UserController和内容中心的UserCenterFeignClient有着同样的方法,且返回结果值也一样,故可以使用继承的思路对代码重构,具体实现方式,大家百度查查(实践过程中踩了个坑,通过这篇文章解决了,希望对大家有帮助-用IDEA把自己的工具类打jar包,并引入到springboot项目中,再把项目打成可执行jar)
PS:feign官方不推荐使用,因为微服务推荐松耦合,继承则会让其变成紧耦合,而大多数互联网公司都采用了此方案,减少代码重复性,故大家按项目实际情况使用
参考:如何使用Feign构造多参数的请求
PS:衔接第四点的feign继承,第一种方式是不可继承的,其余两种可以!
PS:实际选择,原则上尽量用feign,让代码更漂亮、可读、易维护;杜绝使用RestTemplate,便于保持统一的编码风格;事无绝对,合理选择
1、配置连接池(提升15%左右):feign底层除了可以使用urlConnection发送请求,还支持使用Apache HTTPClient以及OKHttp去发送请求,而这两者都是支持连接池的,使用如下:
加依赖 <!-- feign 连接池Tomcat HTTPClient依赖 --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency> 加注解写配置 2、设置合理的日志级别:默认不打印日志,设置成basic,不建议设成full,打印的日志太多,对性能损耗比较多有困惑的小伙伴可点击此链接~
