Feign是一个声明式的http客户端,官方地址:
作用是优雅的实现http请求,用于代替RestTemplate
引入Feign
- 在需要使用的微服务pom文件里引入依赖:
<!--feign客户端依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
在启动类Application.java里添加开启Feign功能的注解:
@MapperScan("cn.itcast.order.mapper") @SpringBootApplication @EnableFeignClients //开启feign的自动装配开关 public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
-
编写Feign客户端
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; @FeignClient("userservice") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
主要是基于Springmvc的注解来声明远程调用的信息
-
在业务层注入UserClient客户端,并调用相关方法
@Autowired private OrderMapper orderMapper; @Autowired private UserClient userClient; public Order queryOrderById(Long orderId) { // 1.查询订单 Order order = orderMapper.findById(orderId);//这个findById方法是OrderMapper的查询方法 //2利用Feign远程调用,查询用户 User user = userClient.findById(order.getUserId());这个findById是我们在Feign客户端定义的方法,不要搞混了 //3 封装user到order order.setUser(user); // 4.返回 return order; }
使用总结:
- 引入依赖
- 添加@EnableFeignClients 注解
- 编写FeignClient接口
- 使用FeignClient中定义的方法代替RestTemplate
Feign的日志级别及其配置
四种日志级别:NONE、BASIC、HEADERS、FULL
日志级别配置
- 方法一:配置文件方式,在application.yml文件做如下配置
#通过配置文件修改feign的日志级别 #全局生效 feign: client: config: default: #这里用default就是全局配置,如果是写服务名称,则是针对某个微服务配置 loggerLevel: Full #日志级别 #局部生效 feign: client: config: userservice: #这里用default就是全局配置,如果是写服务名称,则是针对某个微服务配置 loggerLevel: Full #日志级别
-
方法二:代码方式,先声明一个Bean,即先创建一个配置类
public class DefaultFeignConfiguration { @Bean public Logger.Level logLevel(){ return Logger.Level.BASIC; } }
如果是全局配置,则把该Bean放在启动类的@EnableFeignClients中,配置如下:
@EnableFeignClients(defaultConfiguration = DefaultFeignConfiguration.class/*这里是将刚刚配置好的feign配置类引入,修改日志级别*/) //开启feign的自动装配开关 public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); }
如果是局部配置,则把Bean放在自己创建的Feign客户端的@FeignClient注解里,配置如下
@FeignClient(value = "userservice",configuration = DefaultFeignConfiguration.class) public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
Feign性能优化
Feign底层的客户端实现:
- URLConnection:默认实现,不支持连接池
- Apache HttpClient:支持连接池
- OKHttp:支持连接池
优化方案:
- 使用连接池代替默认的URLConnection
- 日志级别,最好使用basic或者none
这里使用HttpClient来代替默认的URLConnection
先引入依赖
<!--引入HttpClient依赖-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
在application.yml配置连接池
feign:
httpclient:
enabled: true #支持httpclient的开关
max-connections: 200 #连接池最大连接数
max-connections-per-route: 50 #单个路径的最大连接数