Upstash Redis
一个 Redis 计数器示例,用于存储每个区域的函数调用次数的 哈希。可以在 GitHub 上找到代码。
🌐 A Redis counter example that stores a hash of function invocation count per region. Find the code on GitHub.
Redis 数据库设置 #
🌐 Redis database setup
使用 Upstash 控制台 或 Upstash CLI 创建一个 Redis 数据库。
🌐 Create a Redis database using the Upstash Console or Upstash CLI.
选择 Global 类型以将所有边缘位置的延迟降到最低。将 UPSTASH_REDIS_REST_URL 和 UPSTASH_REDIS_REST_TOKEN 复制到你的 .env 文件中。
🌐 Select the Global type to minimize the latency from all edge locations. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN to your .env file.
你可以在 详情 > REST API > .env 下找到它们。
🌐 You'll find them under Details > REST API > .env.
1cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env代码 #
🌐 Code
确保你安装了最新版本的 Supabase CLI。
🌐 Make sure you have the latest version of the Supabase CLI installed.
在你的项目中创建一个新函数:
🌐 Create a new function in your project:
1supabase functions new upstash-redis-counter然后把代码加到 index.ts 文件里:
🌐 And add the code to the index.ts file:
1import { Redis } from 'npm:@upstash/redis@^1'2import { withSupabase } from 'npm:@supabase/server@^1'34console.log(`Function "upstash-redis-counter" up and running!`)56// Open endpoint for testing. In production, implement an authorization layer in the handler or switch the auth mode.7export default {8 fetch: withSupabase({ auth: 'none' }, async (req, ctx) => {9 try {10 const redis = new Redis({11 url: Deno.env.get('UPSTASH_REDIS_REST_URL')!,12 token: Deno.env.get('UPSTASH_REDIS_REST_TOKEN')!,13 })1415 const deno_region = Deno.env.get('DENO_REGION')16 if (deno_region) {17 // Increment region counter18 await redis.hincrby('supa-edge-counter', deno_region, 1)19 } else {20 // Increment localhost counter21 await redis.hincrby('supa-edge-counter', 'localhost', 1)22 }2324 // Get all values25 const counterHash: Record<string, number> | null = await redis.hgetall('supa-edge-counter')26 const counters = Object.entries(counterHash!)27 .sort(([, a], [, b]) => b - a) // sort desc28 .reduce((r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v } }), {29 total: 0,30 regions: {},31 })3233 return Response.json({ counters })34 } catch (error) {35 return Response.json({ error: error.message }, { status: 500 })36 }37 }),38}本地运行 #
🌐 Run locally
1supabase start2supabase functions serve --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env打开 http://localhost:54321/functions/v1/upstash-redis-counter。
🌐 Navigate to http://localhost:54321/functions/v1/upstash-redis-counter.
部署 #
🌐 Deploy
1supabase functions deploy upstash-redis-counter --no-verify-jwt2supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env