Forest是什么?
Forest
是一个高层
的、极简
的轻量级
HTTP调用API框架
,让Java发送HTTP/HTTPS
请求不再难。它比OkHttp和HttpClient更高层,比Feign更轻量,是封装调用第三方restful api client接口的好帮手。
相比于直接使用Httpclient我们不再写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求。
springboot整合forst
1、pom.xml
中引入依赖
<dependency><groupId>com.dtflys.forest</groupId><artifactId>forest-spring-boot-starter</artifactId><version>1.5.36</version>
</dependency>
2、配置文件yml,添加forest的相关配置
forest:max-connections: 1000 # 连接池最大连接数connect-timeout: 3000 # 连接超时时间,单位为毫秒read-timeout: 3000 # 数据读取超时时间,单位为毫秒
3、建一个Interface
比如命名为MyClient
,并创建一个接口方法名为helloForest
,用@Get
注解修饰之。
public interface MyClient {@Get("http://localhost:8080/hello")String helloForest();}
通过@Get
注解,将上面的MyClient
接口中的helloForest()
方法绑定了一个 HTTP 请求, 其 URL 为http://localhost:8080/hello
,并默认使用GET
方式,且将请求响应的数据以String
的方式返回给调用者。
4、扫描接口
友情提示:1.5.1以后版本可以跳过此步,不需要 @ForestScan 注解来指定扫描的包范围
若您已有定义好的 Forest 请求接口(比如名为 com.yoursite.client.MyClient
),那就可以开始愉快使用它了。
只要在Springboot
的配置类或者启动类上加上@ForestScan
注解,并在basePackages
属性里填上远程接口的所在的包名
@SpringBootApplication
@Configuration
@ForestScan(basePackages = "com.yoursite.client")
public class MyApp {...
}
Forest 会扫描@ForestScan
注解中basePackages
属性指定的包下面所有的接口,然后会将符合条件的接口进行动态代理并注入到 Spring 的上下文中。
5、发送请求
然后便能在其他代码中从 Spring 上下文注入接口实例,然后如调用普通接口那样调用即可
@Component
public class MyService {// 注入自定义的 Forest 接口实例@Resourceprivate MyClient myClient;public void testClient() {// 调用自定义的 Forest 接口方法// 等价于发送 HTTP 请求,请求地址和参数即为 helloForest 方法上注解所标识的内容String result = myClient.helloForest();// result 即为 HTTP 请求响应后返回的字符串类型数据System.out.println(result);}}
详情可查看forest的官方文档:🎁 新手介绍 | Forest (dtflyx.com)