Feign
Feign
声明式的http客户端,协助完成http请求的发送
导入Maven依赖
<!-- feign客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类开启注解

编写Java代码
package cn.itcast.order.clients;
import cn.itcast.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author Pickle
* @version V1.0
* @date 2022/12/10 21:40
*/
@FeignClient(name = "/userservice")
public interface UserClient {
@GetMapping(value = "/user/{id}")
User findById(@PathVariable(value = "id") Long id);
}
发送Http请求
@Autowired
private UserClient userClient;
public Order queryOrderById(Long orderId) {
Order order = orderMapper.findById(orderId);
//利用Feign发送http请求
final User user = userClient.findById(order.getUserId());
order.setUser(user);
return order;
}
自定义Feign配置
- application.yml配置
全局配置
feign:
client:
config:
default:
loggerLevel: FULL
单个服务配置
feign:
client:
config:
服务名称:
loggerLevel: FULL
- Java代码配置
配置代码
package cn.itcast.order.config;
import feign.Logger;
import org.springframework.context.annotation.Bean;
/**
* @author Pickle
* @version V1.0
* @date 2022/12/11 9:54
*/
public class DefaultFeignConfiguration {
@Bean
public Logger.Level loggerLevel(){
return Logger.Level.BASIC;
}
}
单个service有效

全局有效

Feign的性能优化-连接池的配置
- 引入依赖
<!-- httpClient的依赖-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
- 配置连接池
feign:
httpclient:
enabled: true # Enables the use of the Apache HTTP Client by Feign
max-connections: 200 # 最大连接数
max-connections-per-route: 50 # 单个路径的最大连接数
Feign抽取Client
将Feign的Client抽取为独立模块,并且把接口有关的PoJo,默认的Feign配置都放到这个模块中,提供给所有消费者使用。
- 将feign独立成一个moudel

- 添加feign-api的依赖
<dependency>
<groupId>cn.itcast.demo</groupId>
<artifactId>feign-api</artifactId>
<version>1.0</version>
</dependency>
- 将Client加入Spring容器中
因为消费者的启动类并不会将Client的实例加入到容器中所以要通过配置的方式将Client加入到Spring容器中。
- 方案一
消费者的启动类中直接在注解中说明要扫描的包

- 方案二
直接指定字节码

浙公网安备 33010602011771号