SpringCloud 声明式服务调用:Feign


Feign 介绍

RestTemplate 方式调用存在的问题:

String url = "http://userservice/user/" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
  • 代码可读性差,编程体验不统一。
  • 参数复杂 URL 难以维护。

解决方案:Feign

  • Feign 是一个声明式的 HTTP 客户端,它用了基于接口的注解方式,可以很方便地实现客户端配置,其作用就是帮助我们优雅的实现 HTTP 请求的发送,解决上面提到的问题。

  • Feign 底层依赖于 Ribbon 实现负载均衡和远程调用。

image


入门案例

Feign 的使用步骤:

  1. 引入依赖
  2. 启动类中添加 @EnableFeignClients 注解
  3. 编写 FeignClient 接口
  4. 使用 FeignClient 中定义的方法代替 RestTemplate,发起 HTTP 请求

消费端引入 Feign 依赖

        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

编写 Feign 调用接口

package com.feign;

import com.domain.Goods;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 *
 * feign声明式接口:用于发起远程调用
 *
 * 1. 定义接口
 * 2. 接口上添加注解 @FeignClient,并设置 value 属性为服务提供者的应用名称
 * 3. 编写调用接口,接口的声明规则和提供方接口保持一致(返回值和方法名可自定义)
 * 4. 注入该接口对象,调用接口方法完成远程调用(自动拼接value与接口URI)
 */
@FeignClient(value="userservice")
public interface UserFeignClient {

    @GetMapping("/user/{id}")
    public User findGoodsById(@PathVariable("id") int id);

}

主要是基于 SpringMVC 的注解来声明远程调用的信息,比如:

  • 服务名称:userservice
  • 请求方式:GET
  • 请求路径:/user/
  • 请求参数:int id
  • 返回值类型:User

Controller 服务调用

package com.controller;

import com.domain.Goods;
import com.feign.GoodsFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 服务调用方
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    // @Autowired
    // private RestTemplate restTemplate;

    @Autowired
    private GoodsFeignClient goodsFeignClient;  // IDEA 提示报错也无需理会

    @GetMapping("/goods/{id}")
    public Goods findOrderByGoodsId(@PathVariable("id") int id) {

        // String url = String.format("http://eureka-provider/goods/findOne/%d", id);
        // Goods goods = restTemplate.getForObject(url, Goods.class);
        Goods goods = goodsFeignClient.findGoodsById(id);
        return goods;
    }
}

启动类添加 Feign 注解

package com;

import com.config.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients  // 开启 Feign 功能
public class ConsumerApp {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class, args);
    }
}

自定义配置

Feign 可以运行自定义配置来覆盖默认配置,可以修改的配置如下:

image

一般我们需要配置的就是日志级别。

配置 Feign 日志有两种方式:

1)配置文件方式

  • 全局生效:
feign:
 client:
   config:
     default:  # 这里用default,则表示全局配置
       loggerLevel: FULL  # 日志级别 
  • 局部生效:
feign:
 client:
   config:
     userservice:  # 这里用服务名称,则是针对某个微服务的配置
       loggerLevel: FULL  # 日志级别 

2)java 代码方式:需要先声明一个 Bean

public class FeignClientConfiguration {
   @Bean
   public Logger.Level feignLogLevel(){
       return Logger.Level.BASIC; 
   }
}

而后如果是全局配置,则把它放到 @EnableFeignClients 这个注解中:

@EnableFeignClients(defaultConfiguration=FeignClientConfiguration.class)

如果是局部配置,则把它放到 @FeignClient 这个注解中:

@FeignClient(value="userservice", configuration=FeignClientConfiguration.class)

Feign 性能优化

Feign 底层的客户端实现:

  • URLConnection:默认实现,不支持连接池
  • Apache HttpClient :支持连接池
  • OKHttp:支持连接池

因此优化 Feign 的性能主要包括:

  • 使用连接池代替默认的 URLConnection
  • 日志级别,最好用 basic 或 none

连接池配置步骤如下:

  1. Feign 添加 HttpClient 的支持:
<!-- httpClient的依赖 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>
  1. 配置连接池:
feign:
 client:
   config:
     default:  # default:全局配置
       loggerLevel: BASIC  # 日志级别:BASIC 就是基本的请求和响应信息 
 httpclient:
   enabled: true  # 开启 feign 对 HttpClient 的支持
   max-connections: 200  # 最大的连接数
   max-connections-per-route: 50  # 每个路径的最大连接数

Feign 最佳实践

方式一(继承):给消费者的 FeignClient 和提供者的 Controller 定义统一的父接口作为标准。

image

存在问题:

image

  • 服务紧耦合
  • 父接口参数列表中的映射不会被继承

方式二(抽取):将 FeignClient 抽取为独立模块(项目),并且把接口有关的 POJO、默认的 Feign 配置都放到这个模块中,提供给所有消费者使用。

image

注意:当定义的 FeignClient 不在 SpringBootApplication 的扫描包范围时,这些 FeignClient 无法使用。有两种方式解决:

// 方式一:指定 FeignClient 所在包
@EnableFeignClients(basePackages="com.feign.clients")

// 方式二:指定 FeignClient 字节码
@EnableFeignClients(clients={UserClient.class})
posted @ 2022-06-04 22:44  Juno3550  阅读(120)  评论(0编辑  收藏  举报