用KV来解决
- User
用KV来解决
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
用KV来解决
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
使用 Cloudflare Workers KV 是解决无状态环境中密钥均匀负载的理想方案。以下是基于 KV 实现的 API 密钥轮转代码:
// Gemini API 反向代理 with KV-based API 密钥轮转
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// 配置 API 密钥
const API_KEYS = [
'YOUR_API_KEY_1',
'YOUR_API_KEY_2',
'YOUR_API_KEY_3'
]
// Gemini API 基础 URL
const GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com'
// KV 命名空间 (需要在 Cloudflare Workers 控制台创建)
// 假设已创建名为 API_KEYS_KV 的命名空间
// 并绑定到代码中的 API_KEYS_COUNTER
async function handleRequest(request) {
// 处理 CORS 预检请求
const corsResponse = handleCors(request)
if (corsResponse) return corsResponse
try {
// 获取 API 密钥
const apiKey = await getNextApiKeyFromKV()
// 构建目标 URL
const url = new URL(request.url)
const targetUrl = `${GEMINI_BASE_URL}${url.pathname}?key=${apiKey}`
// 转发请求
const response = await fetch(targetUrl, {
method: request.method,
headers: request.headers,
body: ['POST', 'PUT', 'PATCH'].includes(request.method)
? await request.clone().arrayBuffer()
: undefined
})
return new Response(response.body, {
status: response.status,
headers: {
...Object.fromEntries(response.headers),
'Access-Control-Allow-Origin': '*'
}
})
} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
})
}
}
// 使用 KV 实现密钥轮转
async function getNextApiKeyFromKV() {
// 获取当前计数器状态
let counters = await API_KEYS_COUNTER.get('key_counters', { type: 'json' })
// 初始化计数器
if (!counters) {
counters = API_KEYS.reduce((acc, key, index) => {
acc[index] = 0
return acc
}, {})
}
// 找出使用次数最少的密钥
let minCount = Infinity
let selectedKeyIndex = 0
for (const [index, count] of Object.entries(counters)) {
if (count < minCount) {
minCount = count
selectedKeyIndex = parseInt(index)
}
}
// 更新计数器
counters[selectedKeyIndex]++
// 写回 KV (使用较短的过期时间,避免计数器无限增长)
await API_KEYS_COUNTER.put('key_counters', JSON.stringify(counters), { expirationTtl: 86400 }) // 1天过期
// 返回选中的密钥
return API_KEYS[selectedKeyIndex]
}
// CORS 处理函数
function handleCors(request) {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': '*'
}
if (request.method === 'OPTIONS') {
return new Response(null, { headers })
}
return null
}
设置说明:
KV 命名空间设置:
API_KEYS_KV 的 KV 命名空间API_KEYS_COUNTER 变量工作原理:
优化考虑:
监控与统计:
这种方案能够在无状态的 Workers 环境中实现真正的均匀负载分配,即使在多实例并发处理请求的情况下也能保持一致性。