目录
  • 前言
  • OpenFeign是什么
    • 原生注解(不推荐)
  • spring注解最佳实践(推荐)
    • 1、引入依赖
    • 2、定义RPC接口
    • 3、自定义Json解码器
    • 4、配置HttpClient线程池
    • 5、编写调用入口
    • 6、RequestInterceptor拦截器扩展
  • Open Feign架构设计图

    前言

    网上对于spring-cloud-starter-openfeign的使用有非常多的说明,此处不再赘述。

    机缘巧合之下,笔者遇到希望轻量级使用Open Feign的场景,即项目中并未使用SpringCloud框架、注册中心等服务发现组件,而只是想简单的做远程http请求调用来解耦微-微服务。

    OpenFeign是什么

    Feign 是netflix提供的开源http client库,目前已经停止维护。

    随后,Spring Cloud官方提供了Open Feign,对Feign做了如下增强:

    • 支持SpringMVC注解
    • 整合Ribbon、Nacos等

    它与Apache HttpClient不同,它可以像调用本地方法一样进行远程方法调用;对,它也是一个RPC框架。

    原生注解(不推荐)

        @RequestLine("POST /postJson")
        @Headers("Content-Type: application/json")
        OrderDto postJson (OrderDto dto);
        @RequestLine("POST /postForm")
        @Headers("Content-Type: application/x-www-form-urlencoded")
        OrderDto postForm (@Param("id") String id, @Param("name") String name);
        @RequestLine("GET /get?id={id}&name={name}")
        String get(@Param("id") String id, @Param("name") String name);
        @RequestLine("GET /get")
        String getByMap(@QueryMap Map<String, Object> param);
        @RequestLine("GET /getById/{id}")
        String getById(@Param("id") String id);

    原生注解@RequestLine有额外的理解成本,我们一般不会使用,上面仅做示例。

    注意:

    1、参数@Param注解需要与@RequestLine中的{xxx} 对应

    2、表单方式需要依赖feign-form

    spring注解最佳实践(推荐)

    从10.5.0版本开始提供了feign-spring4,来适配spring注解。

    使用spring注解需要将contract契约设置为SpringContract。

    1、引入依赖

    <dependency>
       <groupId>io.github.openfeign</groupId>
       <artifactId>feign-core</artifactId>
       <version>11.6</version>
    </dependency>
    <dependency>
       <groupId>io.github.openfeign</groupId>
       <artifactId>feign-spring4</artifactId>
       <version>11.6</version>
    </dependency>
    <dependency>
       <groupId>io.github.openfeign</groupId>
       <artifactId>feign-jackson</artifactId>
       <version>11.6</version>
    </dependency>
    <dependency>
       <groupId>io.github.openfeign</groupId>
       <artifactId>feign-httpclient</artifactId>
       <version>11.6</version>
    </dependency>
    <dependency>
       <groupId>io.github.openfeign.form</groupId>
       <artifactId>feign-form</artifactId>
       <version>3.8.0</version>
    </dependency>

    2、定义RPC接口

    public interface HelloFacade {
        // spring注解用法
        @PostMapping(value = "/postJson", consumes = "application/json")
        OrderDto postJson (@RequestBody OrderDto dto);
        @PostMapping(value = "/postForm", consumes = "application/x-www-form-urlencoded")
        OrderDto postForm (OrderDto dto);
        @GetMapping("/get")
        OrderDto get(@RequestParam("id") Long id, @RequestParam("name") String name);
        @GetMapping("/getByMap")
        OrderDto getByMap(@RequestParam("param") Map<String, Object> param);
        @GetMapping("/getById/{id}")
        OrderDto getById(@PathVariable("id") Long id);
    }

    3、自定义Json解码器

    public class MyJacksonDecoder extends JacksonDecoder {
        @Override
        public Object decode(Response response, Type type) throws IOException {
            if (response.body() == null) {
                return null;
            }
            if (type == String.class) {
                return StreamUtils.copyToString(response.body().asInputStream(), StandardCharsets.UTF_8);
            }
            return super.decode(response, type);
        }
    }

    默认的JacksonDecoder直接拿着字符串做json反序列化,而当我们存在接口返回值是String时,就会格式化报错。

    所以我们集成JacksonDecoder,特殊处理一下String类型即可(String类型不需要经过json格式化)

    4、配置HttpClient线程池

        public static CloseableHttpClient getHttpClient() throws KeyStoreException,
                NoSuchAlgorithmException, KeyManagementException {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTTPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSf).build();
            // 初始化连接管理器
            PoolingHttpClientConnectionManager poolConnManager =
                    new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 同时最多连接数(不设置默认20)
            poolConnManager.setMaxTotal(20);
            // 设置最大路由(不设置默认2)
            poolConnManager.setDefaultMaxPerRoute(10);
            // 此处解释下MaxtTotal和DefaultMaxPerRoute的区别:
            // 1、MaxtTotal是整个池子的大小;
            // 2、DefaultMaxPerRoute是根据连接到的主机对MaxTotal的一个细分;比如:
            // MaxtTotal=400 DefaultMaxPerRoute=200
            // 而只连接到http://www.abc.com时,到这个主机的并发最多只有200;而不是400;
            // 连接到http://www.bac.com 和 http://www.ccd.com时,到每个主机的并发最多只有200;即加起来是400(但不能超过400);
            // 所以起作用的设置是DefaultMaxPerRoute
            // 初始化httpClient
            RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)
                    .setConnectionRequestTimeout(2000)
                    .setSocketTimeout(10000).build();
            return HttpClients.custom()
                    // 设置连接池管理
                    .setConnectionManager(poolConnManager)
                    .setDefaultRequestConfig(config)
                    //  过期连接关闭
                    .evictIdleConnections(60, TimeUnit.SECONDS)
                    .setConnectionTimeToLive(600, TimeUnit.SECONDS)
                    // 设置重试次数
                    .setRetryHandler(new DefaultHttpRequestRetryHandler(1, false)).build();
        }

    OpenFeign默认Http客户端是HttpURLConnection(JDK自带的Http工具),该工具不能配置连接池,生产中使用时性能较差,故我们配置自己的Apache HttpClient连接池。(当然Open Feign也有OkHttp的适配)

    5、编写调用入口

        public static void main(String[] args) throws Exception{
            HelloFacade target = Feign.builder()
                    // spring注解
                    .contract(new SpringContract())
                    .encoder(new FormEncoder(new JacksonEncoder()))
                    .decoder(new MyJacksonDecoder())
                    .client(new ApacheHttpClient(getHttpClient()))
                    .logLevel(Logger.Level.BASIC)
                    .target(HelloFacade.class, "http://localhost:8080");
            String result = target.testStr("hello world");
            System.out.println(result);
        }

    通过Feign.builder 链式初始化,设置Spring注解契约、json编解码器、http客户端工具、日志级别、需要动态代理的接口、以及目标服务的地址。

    6、RequestInterceptor拦截器扩展

    真实业务场景下,我们可能需要统一添加header经过鉴权逻辑,或者根据环境进行转发不同的目标地址,而不是写死。

    那么我们就可以实现OpenFeign提供的RequestInterceptor拦截器接口。

    @Component
    public class TargetUrlRequestInterceptor implements RequestInterceptor {
        @Value("${feign.target.url:http://localhost:7777}")
        private String targetUrl;
        @Override
        public void apply(RequestTemplate template) {
            // 可以添加自定义header
            template.header("customHeader", "123");
            // 可以改变初始化时的目标地址
            template.target(targetUrl);
        }
    }
    

    Open Feign架构设计图

    此处贴一张网上找的架构设计图,供参考学习

    Open Feign之非SpringCloud方式使用示例

    以上就是Open Feign之非SpringCloud方式使用示例的详细内容,更多关于Open Feign非SpringCloud的资料请关注其它相关文章!

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。