本文共 4070 字,大约阅读时间需要 13 分钟。
依赖:
cloud2020 pers.zhang.springcloud 1.0-SNAPSHOT 4.0.0 cloud-consumer-feign-order80 org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-eureka-client pers.zhang.springcloud cloud-api-commons ${project.version} 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 test
配置:application.yml
server: port: 80eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
接口:
@Component@FeignClient(value = "CLOUD-PAYMENT-SERVICE")//指定注册中心的服务名public interface PaymentFeignService { @GetMapping(value = "/payment/get/{id}") public CommonResultgetPaymentById(@PathVariable("id") Long id);}
使用@FeignClient指定被调用的服务名:
Controller:
@RestController@Slf4jpublic class OrderFeignController { @Resource PaymentFeignService paymentFeignService; @GetMapping(value = "/consumer/payment/get/{id}") public CommonResultgetPaymentById(@PathVariable("id") Long id) { return paymentFeignService.getPaymentById(id); }}
启动类:
@SpringBootApplication@EnableDiscoveryClient@EnableFeignClients//开启Feignpublic class OrderFeignMain80 { public static void main(String[] args) { SpringApplication.run(OrderFeignMain80.class, args); }}
启动Eureka,启动被调用的微服务,再启动80端口的调用方:
访问:localhost/consumer/payment/get/35
Feign继承了Ribbon负载均衡,默认使用轮询策略。
提供服务方新增方法模拟超时:
在服务提供方本地测试:
访问:localhost:8001/payment/feign/timeout
:3秒后返回结果如下: 使用Feign在80端口调用8001端口的服务:
访问:localhost/consumer/payment/feign/timeout
因为OpenFeign默认等待时间为1秒,但是服务端处理需要超过1秒,导致Feign客户端不再等待,直接返回报错。
为了避免这种情况,有时候需要设置Feign客户端的超时控制。
修改application.yml
server: port: 80eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/#设置feign客户端超时时间(OpenFeign集成了ribbon,超时由ribbon控制)ribbon: #指的是建立连接所用的时间,适用于网络正常的情况下,两端连接所用的时间 ReadTimeout: 5000 #指的是建立连接后从服务器读取到可用资源所用的时间 ConnectTimeout: 5000logging: level: # feign日志以什么级别监控哪个接口 pers.zhang.springcloud.service.PaymentFeignService: debug
重启80服务,再次访问localhost/consumer/payment/feign/timeout
,3秒后返回信息
Fei提供了日志打印功能,可以通过配置来调整日志级别,从而了解Feign中Http请求的细节。
日志级别:
新增配置类:(指定日志级别)
@Configurationpublic class FeignConfig { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; }}
在application.yml中开启日志,同时指定监控的接口
logging: level: # feign日志以什么级别监控哪个接口 pers.zhang.springcloud.service.PaymentFeignService: debug
启动服务,访问localhost/consumer/payment/get/35
转载地址:http://qspqb.baihongyu.com/