fix async queue and provider key rotation

This commit is contained in:
wlx committed 2026-09-27 18:05:35 +08:00
1 parent 962eef26e5
commit 9750aceb03
4 files changed
+133 -26

No files matched your search

@@ -15,6 +15,8 @@ import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.core.env.Environment;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -27,6 +29,9 @@ public class AsyncProviderClient {
private final SecretCipher cipher;
private final ObjectMapper mapper;
private final Environment environment;
/** Keep rotation state across submit/poll calls; rebuilding a Provider on
* every request otherwise selected the first upstream key forever. */
private final ConcurrentMap<String, AtomicInteger> keyCursors = new ConcurrentHashMap<>();
private final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
public AsyncProviderClient(JdbcTemplate jdbc, SecretCipher cipher, ObjectMapper mapper, Environment environment) {
@@ -97,7 +102,7 @@ public class AsyncProviderClient {
addEnvironmentKeys(keys, "MOYI_TRIPO_API_KEY");
}
if (keys.isEmpty()) throw new ApiException("PROVIDER_NOT_CONFIGURED", "异步渠道尚未配置 API Key", 503);
return new Provider(code, String.valueOf(row.get("base_url")), keys.stream().distinct().toList());
return new Provider(code, String.valueOf(row.get("base_url")), keys.stream().distinct().toList(), keyCursors.computeIfAbsent(id, ignored -> new AtomicInteger()));
} catch (EmptyResultDataAccessException exception) { throw new ApiException("PROVIDER_NOT_CONFIGURED", "异步渠道不存在或已停用", 503); }
}
@@ -116,7 +121,6 @@ public class AsyncProviderClient {
return normalizedCode.contains("tripo") || normalizedUrl.contains("tripo3d");
}
private record Provider(String code, String baseUrl, List<String> apiKeys, AtomicInteger cursor) {
private Provider(String code, String baseUrl, List<String> apiKeys) { this(code, baseUrl, apiKeys, new AtomicInteger()); }
private String nextApiKey() { return apiKeys.get(Math.floorMod(cursor.getAndIncrement(), apiKeys.size())); }
}
}