BUGFIX:为下载flux图片添加重试功能
This commit is contained in:
@@ -3934,11 +3934,48 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
|
||||
}
|
||||
|
||||
public byte[] downloadVideoOrImage(String url) {
|
||||
try (CloseableHttpClient client = HttpClients.createDefault();
|
||||
InputStream in = client.execute(new HttpGet(url)).getEntity().getContent()) {
|
||||
return IOUtils.toByteArray(in);
|
||||
int maxRetries = 3;
|
||||
int retryDelayMs = 1000;
|
||||
IOException lastException = null;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return downloadWithTimeout(url, 30000, 60000);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
lastException = e;
|
||||
log.warn("下载失败 (尝试 {}/{}): {}", attempt, maxRetries, e.getMessage());
|
||||
|
||||
if (attempt < maxRetries) {
|
||||
try {
|
||||
Thread.sleep((long) retryDelayMs * attempt); // 递增延迟
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RuntimeException(ie);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("下载失败,已重试 " + maxRetries + " 次", lastException);
|
||||
}
|
||||
|
||||
private byte[] downloadWithTimeout(String url, int connectTimeout, int socketTimeout) throws IOException {
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectTimeout(connectTimeout)
|
||||
.setSocketTimeout(socketTimeout)
|
||||
.setConnectionRequestTimeout(connectTimeout)
|
||||
.build();
|
||||
|
||||
try (CloseableHttpClient client = HttpClients.custom()
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.build();
|
||||
CloseableHttpResponse response = client.execute(new HttpGet(url))) {
|
||||
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
if (statusCode != 200) {
|
||||
throw new IOException("HTTP Error: " + statusCode);
|
||||
}
|
||||
return IOUtils.toByteArray(response.getEntity().getContent());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user