Feign能在Java代码中比RestTemplate更优雅的发http请求

基本使用

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

        <!--feign对apache httpclient的依赖 这个依赖主要用于优化原有的httpclient-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>

然后创建一个接口, jvm会自动通过动态代理创建这个接口的对象

package cn.itcast.order.clients;

import cn.itcast.order.config.ClientFeignConfiguration;
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(value = "userservice", configuration = ClientFeignConfiguration.class)
public interface UserClient {

    @GetMapping("/user/{id}")
    User getById(@PathVariable("id") Long id);
}

我们配个autoWired, 然后直接调用就好

// 2.使用Feign发送http请求:获取User对象
User user = userClient.getById(order.getUserId());

配置连接池

这步操作需要feign-httpclient依赖

feign:
  httpclient:
    enabled: true
    max-connections: 300
    max-connections-per-route: 60

配置日志记录等级

  1. Java代码的方式: 创建一个这样的类
public class ClientFeignConfiguration {
    @Bean
    public Logger.Level logLevel() {
        return Logger.Level.BASIC;
    }
}

全局配置(在启动类的开关上):

@EnableFeignClients(defaultConfiguration = ClientFeignConfiguration.class)

非全局配置(在创建出来的接口上):

@FeignClient(value = "userservice", configuration = ClientFeignConfiguration.class)
  1. yaml的方式
    default表示全局

    feign:
      client:
     config:
       default:
         logger-level: FULL

    非全局配置示例:

feign:
  client:
    config:
      userservice:  # 这是Feign客户端的名称
        loggerLevel: FULL
      otherservice: # 另一个Feign客户端的名称
        loggerLevel: BASIC

企业级开发最佳实践

把FeignClient相关的代码都抽取成一个模块
企业级开发最佳实践

然后要远程调用的地方还是和以前一样操作, 只不过是换一下导的包
最重要的是: 由于不在同一个模块里面了, 启动类扫描不到原来的东西了
所以::指定basepackage

import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients(basePackages = "cn.itcast.feign.clients",  defaultConfiguration = ClientFeignConfiguration.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}

或者指定单独的某些类

@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients(clients = UserClient.class, defaultConfiguration = ClientFeignConfiguration.class)
public class OrderApplication {

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

}