BUGFIX:为下载flux图片添加重试功能

This commit is contained in:
2026-04-21 17:21:41 +08:00
parent c8dc38575a
commit f6d28fec07

View File

@@ -3934,11 +3934,48 @@ public class GenerateServiceImpl extends ServiceImpl<GenerateMapper, Generate> i
} }
public byte[] downloadVideoOrImage(String url) { public byte[] downloadVideoOrImage(String url) {
try (CloseableHttpClient client = HttpClients.createDefault(); int maxRetries = 3;
InputStream in = client.execute(new HttpGet(url)).getEntity().getContent()) { int retryDelayMs = 1000;
return IOUtils.toByteArray(in); IOException lastException = null;
for (int attempt = 1; attempt <= maxRetries; attempt++) {
try {
return downloadWithTimeout(url, 30000, 60000);
} catch (IOException e) { } 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());
} }
} }