Feign
-
Feign 是一个声明式的REST客户端,它用了基于接口的注解方式,很方便实现客户端配置
Feign - 1
-
Feign最初是由Netfliex公司提供,但不支持SpringMVC注解,后由SpringCloud对其封装,支持了SpringMVC注解,让使用者更易于接受
Feign快速入门
1. 在消费端引入open-feign依赖
<!-- feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 编写Feign调用接口
- 创建一个GoodsFeignClient接口
package com.itheima.consumer.feign;
import com.itheima.consumer.domain.Goods;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* fegin声明式接口,发起远程调用的
* 简化 String url = "http://FEIGN_PROVIDER/goods/findOne/" + id;
* Goods goods = restTemplate.getForObject(url, Goods.class)
*
* 1. 定义接口
* 2.接口上添加注解 @FeginClent, 设置value属性为 服务提供者的应用名称
*
*/
@FeginClient(value = "FEIGN_PROVIDER")
public interface GoodsFeignClient {
@GetMapping("goods/findOne/{id}")
public Goods findGoodsById(@PathVariable("id") int id);
}
3. 在启动类 添加@EnableFeignClients注解,开启Feign功能
@EnableFeginClients //开启Feign的功能
4. 测试调用
- 在Controller中 添加接口
@Autowired
private GoodsFeignClient goodsFeignClient;
@GetMapping("/goods/{id}")
public Goods findGoodsById(@PathVariable("id") int id) {
return goodsFeignClient.findGoodsById(id);
}
Feign其他功能 - 超时设置
- Fagin 底层依赖于Ribbon实现负载均衡和远程调用。
- Ribbon默认1秒超时
ribbon:
connectTimeout: 1000 #链接超市时间 毫秒
ReadTimeout: 1000 #逻辑处理超时时间 毫秒
Feign其他功能 - 日志记录
- Feign 只能记录debug级别的日志信息。
logging:
level:
com.xxxx: debug
- 定义Feign日志级别Bean (config配置类)
/**
* NONE,不记录
*BASIC,记录基本的请求行,响应状态码数据
*HEADERS,记录基本的请求行,响应状态码数据,记录响应头信息
*FULL,记录完整的请求响应数据
*/
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
- 启用该Bean:
@FeignClient(configuration = XxxConfig.class)
网友评论