本文最后更新于91 天前,其中的信息可能已经过时,如有错误请发送邮件到[email protected]
Future和CompletableFuture
CompletableFuture是一种异步编程工具,可以帮助咱们在未来的某个时刻完成一个计算结果。与Future最大的不同是,它可以被显式地完成,意味着咱们可以在任何时候设置它的值。也可以进行链式调用。
// 异步请求并回复 使用chatGPT回答问题
CompletableFuture<String> firstPostFuture = CompletableFuture.supplyAsync(() -> {
try {
String answer = chatGLMApi.doChatGPT(weComTextMsg.getContent());
logger.info("chatGPT回答:{}", answer);
return answer;
} catch (IOException e) {
throw new RuntimeException(e);
}
});
firstPostFuture.thenApplyAsync(answer -> {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
getAppToken(WeChatConstants.WECOM_CORPSECRET, WeChatConstants.WECOM_APP_TOKEN);
String token = WeChatConstants.WECOM_APP_TOKEN.getAccessToken();
logger.info("token:{}", token);
if (StringUtils.isEmpty(token)) {
throw new RuntimeException("token为空");
}
HttpPost post = new HttpPost(WeChatConstants.WECOM_MESSAGE_URL + "?access_token=" + WeChatConstants.WECOM_APP_TOKEN.getAccessToken());
post.addHeader("Content-Type", "application/json");
//封装请求体
WeComTextRes weComTextRes = WeComTextRes.childBuilder()
.touser(weComTextMsg.getFromUserName())
.msgType("text")
.agentid(weComTextMsg.getAgentID())
.text(WeComText.builder().content(answer).build())
.duplicate_check_interval(1800)
.build();
logger.info("请求体封装完毕:{}", JSON.toJSONString(weComTextRes));
StringEntity stringEntity = new StringEntity(JSON.toJSONString(weComTextRes), ContentType.create("text/json", "UTF-8"));
post.setEntity(stringEntity);
try {
CloseableHttpResponse response = httpClient.execute(post);
logger.info("请求结果:{}", response);
return response;
} catch (IOException e) {
throw new RuntimeException(e);
}
});