Spring Cloud - OpenFeign RequestInterceptor 拦截器

(1630条消息) Feign 应用之 RequestInterceptor 拦截器,超实用指南_requestinterceptor使用_柏油的博客-CSDN博客https://blog.csdn.net/ldw201510803006/article/details/126616181可在使用@FeignClient调用远程方法时,增加requestTemplate中的请求参数(header,querystring,body等),Spring会自动装配进使用@FeignClient的请求里

@Configuration
public class FeignRequestConfig {
    @Bean
    public RequestInterceptor headerInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            Enumeration headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    template.header(name, values);
                }
            }
        };
    }
}

代码案例

package com.chinadaas.platform.dsp.kernel.common.config;
 
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
public class FeignConfig implements RequestInterceptor {
 
    @Override
    public void apply(RequestTemplate template) {
        
    }
}
  • 实现接口代码
package com.chinadaas.platform.dsp.kernel.common.config;
 
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Slf4j
@Configuration
public class FeignHandler {
 
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            
        };
    }
}
  • 注解方式代码

配置方案

1、yml 配置:feign.client.config.default.requestInterceptors (会覆盖 Java 配置方式)

feign:
  client:
    config:
      default:
        connectTimeout: 60000
        readTimeout: 60000
        requestInterceptors:
          - com.chinadaas.platform.dsp.kernel.common.config.FeignConfig

2、Application.java 全局配置:@EnableFeignClients 属性 defaultConfiguration = XXX.class

@EnableFeignClients(defaultConfiguration = FeignConfig.class)

3、注解配置:@Configuration + @Bean

  • 如上注解方式代码

4、@FeignClient 配置:属性 configuration = XXX.class

@FeignClient(configuration = FeignHandler.class)

注意:FeignConfig 一定是在消费者使用,而不是放在提供者!

你可能感兴趣的:(Spring,Cloud,spring,cloud,java,spring)