feign请求添加拦截器

引入依赖包

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.0.2.RELEASE</version>
</dependency>

@FeignClient 的 configuration 属性:

Feign 注解 @FeignClient 的 configuration 属性,可以对 feign 的请求进行配置。

包括配置Feign的Encoder、Decoder、 Interceptor 等。

feign 请求添加拦截器,也可以通过这个 configuration 属性 来指定。

feign 请求拦截器 RequestInterceptor

feign 的拦截器,需要实现 RequestInterceptor 接口,重写 apply() 方法。

apply() 方法参数为 RequestTemplate。

RequestTemplate 获取 url :

    //url 的路径为 被调用的服务路径,比如 b-service/user/info
    String url = requestTemplate.url();

RequestTemplate 获取body 参数

    byte[] bodyBytes = requestTemplate.body();
    if (bodyBytes != null) {
    	JSONObject bodyJson = (JSONObject) JSON.toJSON(bodyBytes);
    }

增加 header 参数:

	requestTemplate.header("xxx", "kkk");

示例:

  • FeignInterceptorConfigDemo 配置类:
@Configuration
public class FeignInterceptorConfigDemo {

    /**
     * feign 拦截器
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new MyRequestInterceptor();
    }

    /**
     * 实现拦截器RequestInterceptor
     */
    static class MyRequestInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate template) {
            //示例:添加 header
            template.header("Content-Type", "application/json;charset=utf-8");
            //url 的路径为 被调用的服务路径,比如 b-service/user/info
            String url = template.url();

            //示例:获取body 参数
            byte[] bodyBytes = template.body();
            if (bodyBytes != null) {
                JSONObject bodyJson = (JSONObject) JSON.toJSON(bodyBytes);
                System.out.println("body参数:" + bodyJson);
            }

            //示例:针对特殊的 url 进行处理
            if (url.contains("verifyResult")) {
                //处理逻辑。比如增加 header 参数、 针对特定属性进行拦截等等。
                template.header("userIdTest", "abcde");

            }

        }



    }

}

  • FeignClient 注解 指定 拦截器配置:

在 configuration 属性中,指定配置为 以上设置的 FeignInterceptorConfigDemo 即可添加拦截器。

@FeignClient(name = "myService", configuration = FeignInterceptorConfigDemo.class)
@RequestMapping("/myService")
public interface MyFeignService {

}

posted on 2024-03-18 10:38  乐之者v  阅读(48)  评论(0编辑  收藏  举报

导航