OpenFeign优雅的远程调用

发布时间 2023-04-17 19:46:18作者: 西东怪

OpenFeign

目录旁边可以查询具体的目录结构和跳转

一.快速开发

1.依赖

<!‐‐ openfeign 远程调用 ‐‐>
<dependency>
 	<groupId>org.springframework.cloud</groupId>
 	<artifactId>spring‐cloud‐starter‐openfeign</artifactId>
 </dependency>

2.编写调用接口+@FeignClient注解(注解作用:声明为Feign客户端接口,抽取方法的公有uri地址)

QQ截图20230330000412

@FeignClient(name = "stock-service",path = "/stock")
public interface StockFeignService {

    @RequestMapping("/reduct")
    String reduct();
}

3.调用端在启动类上添加@EnableFeignClients注解

@EnableFeignClients(basePackages = "com.zxy.feign")//开启当前服务支持Feign客户端,作用扫描所有客户端接口

@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }

}

4.注入Feign客户端对象(不再使用RestTemplate进行处理)

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private StockFeignService stockFeignService; //注入Feign客户端

    @RequestMapping("/add")
    public String add(){
        System.out.println("下单成功");
        String msg = stockFeignService.reduct();
        return "hello Feign!"+msg;
    }
}

二.Feign日志配置

1.debug日志级别开启

不管是全局配置还是局部配置都需要开启包的debug基本日志

#springboot的默认日志为info,Feign的日志是debug不会输出 开启对应接口类的包设置为debug级别
logging:
  level:
    com.zxy.feign: debug

2.全局配置

//注意: 此处配置@Configuration注解就会全局生效,如果想指定对应微服务生效,就不能配置
@Configuration
public class FeignConfig {

    @Bean
    public Logger.Level feignLoggerLevel() {
        //输出日志的内容基本FUll  也可以选择其他的
        return Logger.Level.FULL;
    }
}

3.局部配置

方法一 配置类

//1.去掉@Configuration
public class FeignConfig {
    @Bean
    public Logger.Level feignLoggerLevel() {
        //输出日志的内容基本FUll  也可以选择其他的
        return Logger.Level.FULL;
    }
}
//2.对应服务接口@FeignClient中添加配置configuration = FeignConfig.class
@FeignClient(name = "product-service",path = "/product",configuration = FeignConfig.class)
public interface ProductFeignService {

    @RequestMapping("/{id}")
    String get(@PathVariable("id") Integer id);
}

方法二 (yml配置)

通过源码可以看到日志等级有 4 种,分别是:
NONE【性能最佳,适用于生产】:不记录任何日志(默认值)。
BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及
执行时间。
HEADERS:记录BASIC级别的基础上,记录请求和响应的header。
FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body
和元数据。
#feign日志局部日志
feign:
  client:
    config:
      stock-service:
        loggerLevel: BASIC

三.契约配置(基本无用)

​ Spring Cloud 在 Feign 的基础上做了扩展,使用 Spring MVC 的注解来完成Feign的功

能。原生的 Feign 是不支持 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的

注解方式来定义客户端也是可以的,通过配置契约来改变这个配置,Spring Cloud 中默认的

是 SpringMvcContract。

​ Spring Cloud 1 早期版本就是用的原生Fegin. 随着netflix的停更替换成了Open feign

1.修改契约配置,支持Feign原生的注解

方法一(配置类)

/**
* 修改契约配置,支持Feign原生的注解
*@return
*/
@Bean
public Contract feignContract() {
 return new Contract.Default();
}

方法二(yml)

feign:
  client:
  	config:
  		mall‐order: #对应微服务
  			loggerLevel: FULL
  			contract: feign.Contract.Default #指定Feign原生注解契约配置

注意:修改契约配置后,OrderFeignService 不再支持springmvc的注解,需要使用Feign原

生的注解

2.OrderFeignService 中配置使用Feign原生的注解

@FeignClient(value = "mall‐order",path = "/order")
public interface OrderFeignService {
@RequestLine("GET /findOrderByUserId/{userId}")
public R findOrderByUserId(@Param("userId") Integer userId);
}

四.超时时间配置

通过 Options 可以配置连接超时时间和读取超时时间,Options 的第一个参数是连接的超时

时间(ms),默认值是 2s;第二个是请求处理的超时时间(ms),默认值是 5s。

全局配置

@Configuration
public class FeignConfig {
    @Bean
    public Request.Options options() {
    return new Request.Options(5000, 10000);
	}
}

yml中配置

feign:
    client:
       config:
         mall‐order: #对应微服务
             # 连接超时时间,默认5s
             connectTimeout: 5000
             # 请求处理超时时间,默认3s
             readTimeout: 3000

五.修改负载均衡配置

和Nacos一样

OpenFeign服务yml配置和依赖综合

#springboot的默认日志为info,Feign的日志是debug不会输出 开启对应接口类的包设置为debug级别
logging:
  level:
    com.zxy.feign: debug
 #feign
feign:
  client:
    config:
      stock-service:
        loggerLevel: BASIC #feign日志局部日志
      mall‐order: #对应微服务
             # 连接超时时间,默认5s
             connectTimeout: 5000
             # 请求处理超时时间,默认3s
             readTimeout: 3000
父项目的父依赖
<dependencyManagement>
        <dependencies>
            <!--同理也可以把springboot版本控制添加进入,parent留给公司项目父依赖继承-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <!--解决maven单继承问题 可以多继承-->
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--Spring Cloud alibaba的版本控制没通过dependency完成继承-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--spring Cloud版本控制-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>


<!‐‐ openfeign 远程调用 ‐‐>
<dependency>
 	<groupId>org.springframework.cloud</groupId>
 	<artifactId>spring‐cloud‐starter‐openfeign</artifactId>
 </dependency>