一. 什么是Forest
Forest为声明式HTTP客户端框架。将繁复的 HTTP 请求细节封装成 Java 接口 + 注解的形式,不必关心请求发送的具体过程。
管网地址:📐 Springboot环境配置 | Forest
二. 使用Forest
1.引入maven依赖
<dependency>
<groupId>com.dtflys.forest</groupId>
<artifactId>forest-spring-boot-starter</artifactId>
<version>1.5.31</version>
</dependency>
2.application-dev.yml中配置参数
forest:
variables:
url: https://gateway.com/mdm
appId: appid
appsecret: 11111
accessKey: 222222
3.MyClient 配置远程接口的方式
@BaseRequest(
baseURL = "${supplierUrl}", //yml中配置的域名
headers = {
"appId: ${appId}", //yml中配置的appId
"appsecret: ${appsecret}", //yml中配置的appId
"Content-Type: application/json", //传参类型为json
"sign: ${sign}", //签名,使用方法参数@var灵活获取
"timestamp: ${timestamp}" // //时间戳
}
)
public interface MyClient {
/**
* 获取供应商列表
*
* @param timestamp 时间戳
* @param sign 签名
* @param name 供应商名称
* @param organization 供应商组织编码
* @return
*/
@Post(url = "/supplier/api/query") //需要调用的远程方法名称
@Retry(maxRetryCount = "1", maxRetryInterval = "500") //连接数配置,间隔请求时间
String getSupplierList(@Var("timestamp") Long timestamp, //@var注解是为了上面${}中调用
@Var("sign") String sign,
@Body("name") String name,
@Body("organization") String organization);
}
4.本地获取远程资源
@Slf4j
@RestController
public class SupplierController {
@Autowired
private MyClient myClient;
@Value("${forest.variables.appsecret}")
private String appsecret;
@Value("${forest.variables.appId}")
private String appid;
@ApiOperation("供应商列表")
@PostMapping(value = UrlRuleConstants.LIST_QUERY, produces = UrlRuleConstants.PRODUCES)
public R getSupplierList(@RequestBody SupplierReq req) {
String code = "0011";
Long timestamp = System.currentTimeMillis();
String name = "";
String sign = "";
String data = myClient.getSupplierList(timestamp, sign, name, code);
SupplierRes res = JSONUtil.toBean(data, SupplierRes.class);
return R.success(res);
}
5.JSON转对象
import lombok.Data;
import java.util.List;
@Data
public class SupplierRes {
private String code;
private String msg;
private boolean success;
private List<Results> data;
@Data
public class Results {
private String viewUniqueId; //数据id,用来查询明细
private String participantCode;//客商编码
private String participantName;//客商名称
private String socialCreditCode;统一社会信用码
}
}