1、gava-retrying是什么?
官网: gava-retry
在通过项目调用ChatGPT时,会因为网络环境较差情况下出现调用失败的问题。那么如何可以解决这个问题呢?
gava-retrying
是 Google Guava库的一个扩展包。可以为任意函数调用创建可配置的重试机会,是一个灵活方便的 重试组件。包含了多种的重试策略,扩展容易。
2、项目实战
2.1 依赖导入
<!-- https://githubfast.com/rholder/guava-retrying-->
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
2.2 代码修改
原代码:
/**
* AI对话
* @param message
* @param modeId
* @return
*/
public String dochat(long modeId,String message){
DevChatRequest devChatRequest = new DevChatRequest();
devChatRequest.setModelId(modeId);
devChatRequest.setMessage(message);
BaseResponse<DevChatResponse> response = yuCongMingClient.doChat(devChatRequest);
if (response == null){
throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI编译错误");
}
return response.getData().getContent();
}
修改后:
/**
* AI对话
*
* @param message
* @param modeId
* @return
*/
public String dochat(long modeId, String message) {
ThrowUtils.throwIf(modeId < 0, ErrorCode.PARAMS_ERROR, "AI模型ID不合法");
ThrowUtils.throwIf(StringUtils.isBlank(message), ErrorCode.PARAMS_ERROR, "问题不能为空");
DevChatRequest devChatRequest = new DevChatRequest();
devChatRequest.setModelId(modeId);
devChatRequest.setMessage(message);
BaseResponse<DevChatResponse> response = yuCongMingClient.doChat(devChatRequest);
if (response == null) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI响应失败");
}
//重试
Retryer<DevChatResponse> retryer = RetryerBuilder.<DevChatResponse>newBuilder()
//异常重试源,单个
.retryIfExceptionOfType(RuntimeException.class)
//根据结果重试
.retryIfResult(res -> res.getContent().split("【【【【【").length < 3)
//固定时长等待策略
.withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS))
//重试指定次数停止
.withStopStrategy(StopStrategies.stopAfterAttempt(2))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
// 重试结果: 是异常终止, 还是正常返回
log.info("hasException={} asResult={}", attempt.hasException(), attempt.hasResult());
}
})
.build();
try {
DevChatResponse devChatResponse = retryer.call(() -> yuCongMingClient.doChat(devChatRequest).getData());
log.info("AiResult = {}", devChatResponse.getContent());
return response.getData().getContent();
} catch (Exception e) {
log.error("AI响应失败 error = {}", e.getMessage());
}
return "";
}
public String retryDoChat(DevChatRequest devChatRequest){
Retryer<DevChatResponse> retryer = RetryerBuilder.<DevChatResponse>newBuilder()
//异常重试源,单个
.retryIfExceptionOfType(RuntimeException.class)
//根据结果重试
.retryIfResult(res -> res.getContent().split("【【【【【").length < 3)
//固定时长等待策略
.withWaitStrategy(WaitStrategies.fixedWait(5, TimeUnit.SECONDS))
//重试指定次数停止
.withStopStrategy(StopStrategies.stopAfterAttempt(2))
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
// 重试结果: 是异常终止, 还是正常返回
log.info("hasException={} asResult={}", attempt.hasException(), attempt.hasResult());
}
})
.build();
try {
DevChatResponse devChatResponse = retryer.call(() -> yuCongMingClient.doChat(devChatRequest).getData());
log.info("AiResult = {}", devChatResponse.getContent());
return devChatResponse.getContent();
} catch (Exception e) {
log.error("AI响应失败 error = {}", e.getMessage());
}
return "";
}
2.3 测试
这里输入正确结果:
@Test
void test() {
long modelId = 1660101421632061442L;
String message = "分析需求:\n" +
"分析网站用户的增长情况\n" +
"原始数据:\n" +
"日期,用户数\n" +
"1号,10\n" +
"2号,20\n" +
"3号,30";
String res = aiManager.dochat(modelId, message);
final String str = "【【【【【";
String[] aiRes = res.split(str);
System.out.println(aiRes.length);
ThrowUtils.throwIf(aiRes.length < 3, ErrorCode.SYSTEM_ERROR, "AI返回结果有误");
String genChart = aiRes[ 1 ].trim();
String genRes = aiRes[ 2 ].trim();
System.out.println(genChart);
System.out.println(genRes);
}
反应结果:
错误示范:
修改成一个错误的modeId
查看结果:
可以看到,是重试了两次。