Forest声明式HTTP客户端框架漫谈

Forest 是一款声明式的 Java 开源 HTTP 框架,相比它的前辈 Httpclient 和 OkHttp 更简明易懂、也更容易维护,使用过程中非常丝滑故想分享给更多的朋友,此处我们进行简单的介绍和使用说明。

一. 什么是Forest

Forest为声明式HTTP客户端框架。将繁复的 HTTP 请求细节封装成 Java 接口 + 注解的形式,不必关心请求发送的具体过程。

普通HTTP请求,例使用hutool的HttpUtil:

import cn.hutool.http.HttpUtil;

String resule = HttpUtil.get("http://ditu.amap.com/service/regeo?longitude={lng}&latitude={lat}");

Forest示例:

public interface MyClient {
    @Get("http://localhost:8080/hello")
    String helloForest();
}


@Autowired
private MyClient client;

public void execute(){
    client.helloForest();
}

二. 使用Forest

  1. 引入依赖(maven)

    <dependency>
        <groupId>com.dtflys.forest</groupId>
        <artifactId>forest-spring-boot-starter</artifactId>
        <version>1.5.31</version>
    </dependency>
    
  2. Forest配置

    Forest是基于约定大于配置的理念进行设计的,如果已经添加好了forest-spring-boot-starter依赖,基本上可以什么都不配置。但是也可以做一些简单的配置,具体可以参考Springboot环境配置项

    forest:
      max-connections: 1000        # 连接池最大连接数
      connect-timeout: 3000        # 连接超时时间,单位为毫秒
      read-timeout: 3000           # 数据读取超时时间,单位为毫秒
    
  3. 定义接口

    public interface MyClient {
    
        /**
         * 测试forest的get请求
         * @param param1 参数1
         * @param param2 参数2
         * @return
         */
        @Get("http://localhost:8080/testGetForest?param1={param1}&param2={param2}")
        JSONObject getData(String param1, String param2);
    
        /**
         * 测试forest的post请求
         * @param data body传参
         * @return
         */
        @Post("http://localhost:8080/testPostForest")
        JSONObject postData(@JSONBody JSONObject data);
    }
    
  4. 实际调用

    @Service
    public class MyService{
        
        @Autowired
        private MyClient client;
        
        public void run(){
            client.getData("param1", "param2");
            client.postData(new JSONObject());
        }
    }
    

三. 总结

使用Forest极大的提高了便利性,也能够使得代码更容易维护。如果我们使用了IDEA,那么还可以搭配官方插件ForextX进行使用。

参考资料:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值