Forest是一个高层的、极简的声明式HTTP调用API框架
相比于直接使用Httpclient您不再用写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求
maven
<dependency>
<groupId>com.dtflys.forest</groupId>
<artifactId>forest-spring-boot-starter</artifactId>
<version>1.5.36</version>
</dependency>
在application.yaml
/ application.properties
中配置的 HTTP 基本参数
forest:
max-connections: 1000 # 连接池最大连接数
connect-timeout: 3000 # 连接超时时间,单位为毫秒
read-timeout: 3000 # 数据读取超时时间,单位为毫秒
扫描接口,在Springboot
的配置类或者启动类上加上@ForestScan
注解,并在basePackages
属性里填上远程接口的所在的包名
@SpringBootApplication
@Configuration
@ForestScan(basePackages = "com.yoursite.client")
public class MyApp { }
使用方式,创建一个interface
,用@Get
注解修饰之。
import com.dtflys.forest.annotation.JSONBody;
import com.dtflys.forest.annotation.Post;
import com.dtflys.forest.annotation.Retry;
import com.dtflys.forest.annotation.Var;
public interface MyClient {
@Get("http://localhost:8080/hello")
String helloForest();
/**
* 用户中心登录
*
* @param req
* @return
*/
@Post(url = "{url}/api/v1/login/autoLoginOnlyByAuthCode"
, contentType = "application/json"
, connectTimeout = 2000
, readTimeout = 2000)
@Retry(maxRetryCount = "1", maxRetryInterval = "100")
String login(@Var("url") String url, @JSONBody AutoLoginOnlyByAuthCodeReq req);
}
发送请求
@Component
public class MyService {
// 注入自定义的 Forest 接口实例
@Resource
private MyClient myClient;
public void testClient() {
// 调用自定义的 Forest 接口方法
// 等价于发送 HTTP 请求,请求地址和参数即为 helloForest 方法上注解所标识的内容
String result = myClient.helloForest();
// result 即为 HTTP 请求响应后返回的字符串类型数据
System.out.println(result);
}
}