源码:https://gitee.com/GXQ205153964/sleuth-parent.git
Feign简介:- Feign 是一个声明式的REST客户端,他用了基于接口的注解方式,很方便实现客户端配置。
- 使用Feign不用像 Ribbon一样远程调用还得拼接字符串,
- Feign最初由Netflix公司提供,但不支持SpringMVC注解,后由SpringCloud对其改装,支持了SpringMVC注解,让使用易于接受。
流程:
- 在消费端引入open-feign依赖
- 编写Feign调用接口
- 在启动类 添加@EnableFeignClients注解,开启Feign功能
consumer provider EurekaServer 可以直接复制以下代码:
备份:里面的SpringCloudEureka_consumer Eureka_provider EurekaServer
稍微修改一下里面的代码
只修改了consumer代码,其他代码不动
导入consumer依赖:
org.springframework.cloud spring-cloud-starter-openfeign
编写接口GoodsFeignClient
package com.gao.feign; import com.gao.domain.Goods; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient(value = "FEIGN-PROVIDER") public interface GoodsFeignClient { @GetMapping("/goods/findOne/{id}") public Goods findGoodsById(@PathVariable("id") int id); }
OrderController
//服务的调用方 @RestController @RequestMapping("/order") public class OrderController { @Autowired private GoodsFeignClient goodsFeignClient; @GetMapping("/goods/{id}") public Goods findGoodsById(@PathVariable("id") int id){ // 原来的代码 // String url = "http://EUREKA-PROVIDER/goods/findOne/"+id; // Goods goods = restTemplate.getForObject(url,Goods.class); Goods goods= goodsFeignClient.findGoodsById(id); return goods; } }Feign 超时设置:
- Feign底层依赖于Ribbon实现负载均衡的远程
- Feign是对Ribbon上层做的一个封装,可以使用Ribbon的一切功能
- Ribbon默认1秒超时
- 超时设置
ribbon:
connectTimeout:1000 连接超时 1000毫秒
ReadTimeout:1000 逻辑处理超时 1000毫秒
修改provider的GoodsController,让程序睡眠2秒。//当前线程睡2秒 try{ Thread.sleep(2000); }catch (InterruptedException e){ e.printStackTrace();测试结果:
consumer
设置Ribbon的超时时间(consumer)
#设置Ribbon的超时时间 ribbon: ConnectTimeout: 1000 ReadTimeout: 3000
重启consumer重新获取
Feign 日志记录- 记录的是整个请求响应链路过程中的传输的http协议的数据
Feign 只能记录debug级别的日志信息(controller)
#设置当前日志级别debug,feign只支持记录debug级别的日志 logging: level: com.gao: debug
定义Feign日志级别Bean
package com.gao.config; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignLogConfig { @Bean public Logger.Level level(){ return Logger.Level.FULL; } }
启用该Bean:(consumer GoodsFeignClient接口)
@FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
测试:
重启consumer,日志信息