1.openfeign使用在客户端,就是服务调用方
2.新建工程,导入如下依赖
org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-zookeeper-discovery com.lyg.springcloud cloud-api-commons 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test
3.yml总添加如下配置
#eureka配置
eureka:
instance:
hostname: localhost #eureka服务端实例名称
client:
# 客户端不注册也能调用服务端
register-with-eureka: false
# false表示我自己就是注册中心,职责是维护实例,不需要去检索服务
fetch-registry: true
service-url:
# 注册地址
#单机版
# defaultZone: http://localhost:7001/eureka/
# 集群配置
defaultZone: http://euraka7001.com:7001/eureka/,http://euraka7002.com:7002/eureka/
3.在主启动类上添加开启openfeign注解
@EnableFeignClients
4.编写feign接口
@Component
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
@GetMapping("payment/getPaymentById/{id}")
CommonResult getPaymentById(@PathVariable("id") Long id);
}
注意:openFeign是对feign的更进一步封装,接口上支持springmvc注解
这个接口和调服务端的接口项目对应
5.测试,编写消费方controller调用测试
@RestController
public class OrderFeignController {
@Autowired
private PaymentFeignService paymentFeignService;
@GetMapping("consumer/payment/getPaymentById/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
CommonResult paymentById = paymentFeignService.getPaymentById(id);
return paymentById;
}
}
6测试结果
7.openfeign超时控制
(1)在yml添加配置
feign:
client:
config:
default:
#建立连接所用的时间,适用于网络状况正常的情况下,两端连接所需要的时间
ConnectTimeOut: 5000
#指建立连接后从服务端读取到可用资源所用的时间
ReadTimeOut: 5000
如果访问时间超过5秒钟会返回超时报错,openfeign的默认超时时间不知道是多少,我测试超时8秒默认还能请求到
8.frign提供了日志day功能,我们可以通过配置来调整日志级别,从而了解feign中http请求细节,对feign调用的监控及输出
feign日志级别:
1.新建一个配置类,配置日志级别
@Configuration
public class FeignConfig {
//最全的日志级别
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
2.yml配置文件中开启日志级别
logging:
level:
# feign日志以什么级别控制哪个接口打印
com.lyg.sppringcloud.service.PaymentFeignService: debug
3.启动测试



