Spring Cloud Alibaba-Feign全局配置自定义和支持的配置项

简介: Spring Cloud Alibaba-Feign全局配置自定义和支持的配置项

一、全局配置自定义


1、代码配置


  • 方式一:让父子上下文ComponentScan重叠(强烈不建议使用)


@Configuration
public class StockFeignConfiguration {
    /**
     * 日志级别
     * 通过源码可以看到日志等级有 4 种,分别是:
     * NONE:不输出日志。
     * BASIC:只输出请求方法的 URL 和响应的状态码以及接口执行的时间。
     * HEADERS:将 BASIC 信息和请求头信息输出。
     * FULL:输出完整的请求信息。
     */
    @Bean
    public Logger.Level level(){
        return Logger.Level.FULL;
    }
}
复制代码


  • 方式二【唯一正确的途径】: EnableFeignClients(defaultConfiguration=xxx.class)

image.png
image.png



2、属性配置


logging:
  level:
    com.nx: debug
feign:
  client:
    config:
      default:
        loggerLevel: full
复制代码



二、 支持的配置项


1、契约配置


Spring Cloud 在 Feign 的基础上做了扩展,可以让 Feign 支持 Spring MVC 的注解来调用。原生的 Feign 是不支持 Spring MVC 注解的,如果你想在 Spring Cloud 中使用原生的注解方式来定义客户端也是 可以的,通过配置契约来改变这个配置,Spring Cloud 中默认的是 SpringMvcContract。


1.1代码方式


/**
     * 修改契约配置,这里仅仅支持Feign原生注解
     * 这里是一个扩展点,如果我们想支持其他的注解,可以更改Contract的实现类。
     * @return
     */
    @Bean
    public Contract feignContract(){
        return new Contract.Default();
    }
复制代码


注意:这里修改了契约配置之后,我们就只能用Fegin的原生注解


image.png

1.2 属性方式

image.png



2、编解码


Feign 中提供了自定义的编码解码器设置,同时也提供了多种编码器的实现,比如 Gson、Jaxb、Jackson。 我们可以用不同的编码解码器来处理数据的传输。。

扩展点:Encoder & Decoder


默认我们使用:SpringEncoder和SpringDecoder


package feign.codec;
public interface Encoder {
  void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException;
}
复制代码


package feign.codec;
public interface Decoder {
  Object decode(Response response, Type type) throws IOException, DecodeException, FeignException;
}
复制代码


2.1 代码方式


@Bean
public Decoder decoder(){
    return new CustomDecoder();
}
@Bean
public Encoder encoder(){
    return new CustomEncoder();
}
复制代码


2.2 属性方式


feign:
  client:
    config:
      #想要调用的微服务的名称
      msb-user:
        encoder: com.xxx.CustomDecoder
        decoder: com.xxx..CustomEncoder
复制代码



3、拦截器


通常我们调用的接口都是有权限控制的,很多时候可能认证的值是通过参数去传递的,还有就是通过请求头 去传递认证信息,比如 Basic 认证方式。


3.1 扩展点:


package feign;
public interface RequestInterceptor {
  void apply(RequestTemplate template);
}
复制代码


3.2 使用场景


  1. 统一添加 header 信息;


  1. 对 body 中的信息做修改或替换;


3.3 自定义逻辑


package com.msb.order.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    private String tokenId;
    public FeignAuthRequestInterceptor(String tokenId) {
        this.tokenId = tokenId;
    }
    @Override
    public void apply(RequestTemplate template) {
        template.header("Authorization",tokenId);
    }
}
复制代码


package com.msb.order.configuration;
import com.msb.order.interceptor.FeignAuthRequestInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
    @Value("${feign.tokenId}")
    private String tokenId;
    /**
     * 自定义拦截器
     * @return
     */
    @Bean
    public FeignAuthRequestInterceptor feignAuthRequestInterceptor(){
        return new FeignAuthRequestInterceptor(tokenId);
    }
}
复制代码


feign:
  tokenId: d874528b-a9d9-46df-ad90-b92f87ccc557
复制代码


在msb-stock项目中增加springmvc中的拦截器

拦截器代码:


package com.msb.stock.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = true;
        // 逻辑认证
        String authorization = request.getHeader("Authorization");
        log.info("获取的认证信息 Authorization:{}",authorization);
        if(StringUtils.hasText(authorization)){
            return true;
        }
        return false;
    }
}
复制代码


增加类配置:


package com.nx.user.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor());
    }
复制代码


优先级:


全局代码<全局属性<细粒度代码<细粒度属性
复制代码



4、Client 设置


Feign 中默认使用 JDK 原生的 URLConnection 发送 HTTP 请求,我们可以集成别的组件来替换掉 URLConnection,比如 Apache HttpClient,OkHttp。


4.1 扩展点


Feign发起调用真正执行逻辑:feign.Client#execute (扩展点)


public interface Client {
  Response execute(Request request, Options options) throws IOException;
 }
复制代码


4.2 配置Apache HttpClient


  1. 引入依赖


<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>
复制代码


  1. 修改yml配置
    开启feign ,这里可以不用配置,可以参考源码分析


feign:
  httpclient:
    #使用apache httpclient做请求,而不是jdk的HttpUrlConnection
    enabled: true
    # feign最大链接数 默认200
    max-connections: 200
    #feign 单个路径的最大连接数  默认 50
    max-connections-per-route: 50
复制代码


  1. 源码分析 FeignAutoConfiguration


image.png

此时默认增加一个ApacheHttpCient实现类

image.png


4.3 设置OkHttp


  1. 引入依赖


<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-okhttp</artifactId>
</dependency>
复制代码


  1. 增加配置


feign:
  okhttp:
    enabled: true
    #线程池可以使用httpclient的配置   
  httpclient:
    max-connections: 200
    max-connections-per-route: 50
复制代码


image.png

3、源码分析 FeignAutoConfiguration

image.png


5、超时配置


通过 Options 可以配置连接超时时间和读取超时时间,Options 的第一个参数是连接的超时时间(ms), 默认值是 10s;第二个是请求处理的超时时间(ms),默认值是 60s。


Request.Options


image.png

5.1 代码配置


@Bean
public Request.Options options(){
    return new Request.Options(2000,50000);
}
复制代码


msb-stock改造


@GetMapping("query")
public User queryInfo(User user){
    try {
        Thread.sleep(10*1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return user;
}
复制代码

image.png


相关文章
|
24天前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
16天前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
16天前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
2月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
563 0
|
10天前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
160 4
|
16天前
|
监控 安全 Java
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
Spring Boot 通过 Actuator 模块提供了强大的健康检查功能,帮助开发者快速了解应用程序的运行状态。默认健康检查可检测数据库连接、依赖服务、资源可用性等,但在实际应用中,业务需求和依赖关系各不相同,因此需要实现自定义健康检查来更精确地监控关键组件。本文介绍了如何使用 @HealthEndpoint 注解及实现 HealthIndicator 接口来扩展 Spring Boot 的健康检查功能,从而提升系统的可观测性与稳定性。
使用 @HealthEndpoint 在 Spring Boot 中实现自定义健康检查
|
17天前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
探索Spring Boot的@Conditional注解的上下文配置
|
1月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
680 10
|
2月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
733 0