SpringCloudAlibaba - 整合 Feign 实现远程 HTTP 调用

前言

FeignNetflix开源的声明式HTTP客户端,致力于让编写http client更加简单,Feign可以通过声明接口自动构造请求的目标地址完成请求


环境

Spring Cloud Hoxton.SR9 + Spring Cloud Alibaba 2.2.6.RELEASE
FeignNetflix公司产品,目前已停止更新,文章中使用的是OpenFeign,是Spring社区开发的组件


简单示例

content-center

  • pom.xml
<!-- openfeign -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 启动类ContentCenterApplication.java
@EnableFeignClients
public class ContentCenterApplication {
}
  • TestController.java
import com.coisini.contentcenter.feignclient.TestFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestController {

     private final TestFeignClient testFeignClient;

	/**
     * 整合Feign
     * @return
     */
    @GetMapping("test4")
    public String test4() {
        return testFeignClient.test("Coisini");
    }
    
}
  • TestFeignClient.java
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @FeignClient(name = "user-center") 
 * name 要请求的微服务的名称
 */
@FeignClient(name = "user-center")
public interface TestFeignClient{

    /**
     * test接口被调用时,feign会构造出 url
     * http://user-center/test/{name} 完成请求
     * @param name
     * @return
     */
    @GetMapping("/test/{name}")
    String test(@PathVariable String name);

}

user-center

  • TestController.java
@RestController
@Slf4j
public class TestController {

    @GetMapping("/test/{name}")
    public String test(@PathVariable String name) {
        log.info("请求...");
        return "hello " + name;
    }

}

示例测试结果

在这里插入图片描述


...至此,已完成Feign的整合


Feign 的组成和支持的配置项

Feign 的组成

接口 作用 默认值
Feign.Builder Feign的入口 Feign.Builder
Client Feign底层请求方式 和Ribbon配合时 LoadBalancerFeignClient
不和Ribbon配合时 feign.Client.Default
Contract 契约,注解支持 SpringMvcContract
Encoder 编码器,用于将对象转换成HTTP请求消息体 SpringEncoder
Decoder 解码器,将响应消息转换成对象 ResponseEntityDecoder
Logger 日志管理器 Slf4jLogger
RequestInterceptor 用于为每个请求添加通用逻辑

Feign 支持的配置项

代码配置支持的配置项

配置项 作用
Logger.Level 指定日志级别
Retryer 指定重试策略
ErrorDecoder 指定错误解码器
Request.Options 超时时间
Collection< RequestInterceptor> 拦截器
SetterFactory 用于设置Hystrix的配置属性,整合Hystrix才会生效

配置属性支持的配置项

feign.client.config: 
  <feignName>:
    connectTimeout: 5000 # 连接超时时间
    readTimeout: 5000 # 读取超时时间
    loggerLevel: full # 日志级别
    errorDecoder: com.example.SimpleErrorDecoder # 错误解码器
    retryer: com.example.SimpleRetryer # 重试策略
    requestInterceptors: com.example.FooRequestInterceptor # 拦截器
    decode404: false # 是否对404错误码解码
    encoder: com.example.SimpleEncoder # 编码器
    decoder: com.example.SimpleDecoder # 解码器
    contract: com.example.SimpleContract # 契约

Feign 的日志

Feign 的日志级别

  • feign默认不打印任何日志
级别 打印内容
NONE(默认值) 不记录任何日志
BASIC 仅记录请求方法、URL、响应状态代码以及执行时间
HEADERS BASIC级别的基础上,记录请求和响应的header
FULL 记录请求和响应的header、body和元数据

自定义配置 Feign 的日志级别

Java 代码配置方式

  • UserCenterFeignConfiguration.java
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * @Description 用户中心 Feign 配置类
 */
public class UserCenterFeignConfiguration {

    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }

}
  • UserCenterFeignClient.java
@FeignClient(name = "user-center", configuration = UserCenterFeignConfiguration.class)
public interface UserCenterFeignClient {
	...
}
  • application.yml
logging:
  level:
    # feign 的日志级别是建立在接口日志级别基础上的
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug
  • 访问接口查看feign日志

在这里插入图片描述


yml 属性配置方式

  • application.yml,实现效果同上
logging:
  level:
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug

# 自定义配置 feign 日志级别
feign:
  client:
    config:
      # 调用的微服务名称
      user-center:
        loggerLevel: full

全局配置 Feign 的日志级别

Java 代码配置方式

  • GlobalFeignConfiguration.java
import feign.Logger;
import org.springframework.context.annotation.Bean;

/**
 * @Description Feign 全局配置类
 */
public class GlobalFeignConfiguration {

    @Bean
    public Logger.Level level() {
        // feign 日志级别 FULL
        return Logger.Level.FULL;
    }

}
  • 启动类ContentCenterApplication.java
@EnableFeignClients(defaultConfiguration = GlobalFeignConfiguration.class)
@SpringBootApplication
public class ContentCenterApplication {
	...
}
  • application.yml
logging:
  level:
    com.coisini.contentcenter.feignclient.UserCenterFeignClient: debug
  • 接口日志打印

在这里插入图片描述


yml 属性配置方式

  • application.yml
# 自定义配置 feign 日志级别
feign:
  client:
    config:
      # 全局配置
      default:
        loggerLevel: full
  • 实现效果同上

Feign 日志级别配置方式总结

  • 配置方式优先级:全局代码配置 < 全局属性配置 < 自定义代码配置(细粒度) < 自定义属性配置(细粒度)
  • 建议尽量使用属性配置

项目源码



- End -
白嫖有风险
点赞加收藏
posted @ 2021-09-23 18:06  Maggieq8324  阅读(254)  评论(0)    收藏  举报