博客
关于我
一款直击痛点的优秀http框架,让我超高效率完成了和第三方接口的对接
阅读量:414 次
发布时间:2019-03-06

本文共 2780 字,大约阅读时间需要 9 分钟。

背景

在业务拓展过程中,我们需要与众多第三方服务商进行API对接。这些服务商提供的API规范各不相同,有的遵循RESTFUL标准,有的则基于传统的HTTP协议。一些API需要通过header传递签名,有些则需要SSL双向认证,而有的仅需SSL单向认证。此外,序列化方式也存在差异,有的使用JSON,有的采用XML。这种多样化的API规范差异给开发工作带来了诸多挑战。

在这一切复杂性中,我发现了一款优秀的开源框架——Forest。它能够有效屏蔽不同API所带来的所有差异,通过简单的配置就可以完成复杂的HTTP调用,实现了对第三方服务API的统一接口管理。

上手

Forest框架支持Spring Boot的自动装配,只需引入相应的依赖即可快速开始使用。具体步骤如下:

  • 在项目依赖中添加Forest Starter包:
  • com.dtflys.forest
    spring-boot-starter-forest
    1.3.0
    1. 定义自己的接口类,Forest会自动扫描这些接口并生成代理类:
    2. public interface MyClient {    @Request(url = "http://baidu.com")    String simpleRequest();    @Request(        url = "http://ditu.amap.com/service/regeo",        dataType = "json"    )    Map getLocation(@DataParam("longitude") String longitude, @DataParam("latitude") String latitude);}
      1. 在启动类中配置扫描包并注入接口:
      2. @SpringBootApplication@ForestScan(basePackages = "com.example.demo.forest")public class DemoApplication {    public static void main(String[] args) {        SpringApplication.run(DemoApplication.class, args);    }}
        1. 在业务逻辑中注入并使用代理接口:
        2. @Autowiredprivate MyClient myClient;@Overridepublic void yourMethod() throws Exception {    Map result = myClient.getLocation("124.730329", "31.463683");    System.out.println(JSON.toJSONString(result, true));}

          Forest还支持日志打印功能,打印请求细节和返回结果,可根据需求配置日志级别。

          特点

          Forest作为一款专注于简化第三方API对接的开源框架,具有以下优势:

        3. 高效便捷:通过配置或注解即可定义HTTP请求,极大降低了对每个API的依赖。
        4. 底层支持:封装了Apache HttpClient和OkHttp,避免了手动处理底层协议细节。
        5. 灵活性强:支持多种请求方法和数据序列化格式,适配各种API风格。
        6. 配置简单:通过注解定义URL、请求方法、数据类型等,减少了繁琐的配置。
        7. Forest还支持SSL双向认证、模板表达式、过滤器、异步调用等功能,极大提升了开发效率。

          两个很棒的功能

          4.1 模板表达式和参数映射绑定

          Forest的模板表达式功能非常强大,支持通过参数名称或位置进行数据绑定。例如:

          @Request(    url = "${base}/send?un=${1}&pw=${2}",    type = "get",    dataType = "json")public Map send(    String base,    String userName,    String password,    String phone);

          或者通过参数名称绑定:

          @Request(    url = "${base}/send?un=${un}&pw=${pw}",    type = "get",    dataType = "json")public Map send(    @DataVariable("base") String base,    @DataVariable("un") String userName,    @DataVariable("pw") String password,    @DataVariable("ph") String phone);

          此外,Forest还支持将对象序列化为JSON或XML,并可通过headers或body传递数据。

          4.2 HTTPS支持

          Forest对HTTPS的支持非常完善,尤其是双向证书的配置。例如:

          @Request(    url = "${base}/pay",    contentType = "application/json",    type = "post",    dataType = "json",    keyStore = "pay-keystore",    data = "${json($0)}")public PayResponse pay(PayRequest request);

          application.yml中配置证书信息:

          forest:    ssl-key-stores:        - id: pay-keystore            file: test.keystore            keystore-pass: 123456            cert-pass: 123456            protocols: SSLv3

          通过简单配置,Forest能轻松处理HTTPS双向认证,实现安全的API对接。

          最后

          Forest框架涵盖了诸多功能,适合处理复杂的HTTP调用场景。如果您对以上内容感兴趣,建议访问其官方文档获取更多信息。

          Forest与Feign的区别在于,Forest更注重配置的简单性和易用性,而不像Feign那样紧密依赖Spring Cloud。Forest的目标是为开发人员提供一个高效、灵活的HTTP客户端工具,帮助您快速完成第三方API对接。

    转载地址:http://jyxkz.baihongyu.com/

    你可能感兴趣的文章
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>