Feign

Feign

声明式的http客户端,协助完成http请求的发送

导入Maven依赖

<!-- feign客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

启动类开启注解

image-20221210213957436

编写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配置

  1. application.yml配置

全局配置

feign:
client:
config:
default:
loggerLevel: FULL

单个服务配置

feign:
client:
config:
服务名称:
loggerLevel: FULL
  1. 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有效

image-20221211095959967

全局有效

image-20221211100117215

Feign的性能优化-连接池的配置

  1. 引入依赖
<!-- httpClient的依赖-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
  1. 配置连接池
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配置都放到这个模块中,提供给所有消费者使用。

  1. 将feign独立成一个moudel

image-20221211103946990

  1. 添加feign-api的依赖
<dependency>
<groupId>cn.itcast.demo</groupId>
<artifactId>feign-api</artifactId>
<version>1.0</version>
</dependency>
  1. 将Client加入Spring容器中

因为消费者的启动类并不会将Client的实例加入到容器中所以要通过配置的方式将Client加入到Spring容器中。

  1. 方案一

消费者的启动类中直接在注解中说明要扫描的包

image-20221211111801272

  1. 方案二

直接指定字节码

image-20221211111949842

posted @   破忒头头  阅读(207)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示