Skip to content
Edge Functions

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.

cp 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:

supabase functions new upstash-redis-counter

然后把代码加到 index.ts 文件里:

🌐 And add the code to the index.ts file:

import { withSupabase } from 'npm:@supabase/server@^1'
import { Redis } from 'npm:@upstash/redis@^1'
console.log(`Function "upstash-redis-counter" up and running!`)
// Open endpoint for testing. In production, implement an authorization layer in the handler or switch the auth mode.
export default {
fetch: withSupabase({ auth: 'none' }, async (req, ctx) => {
try {
const redis = new Redis({
url: Deno.env.get('UPSTASH_REDIS_REST_URL')!,
token: Deno.env.get('UPSTASH_REDIS_REST_TOKEN')!,
})
const deno_region = Deno.env.get('DENO_REGION')
if (deno_region) {
// Increment region counter
await redis.hincrby('supa-edge-counter', deno_region, 1)
} else {
// Increment localhost counter
await redis.hincrby('supa-edge-counter', 'localhost', 1)
}
// Get all values
const counterHash: Record<string, number> | null = await redis.hgetall('supa-edge-counter')
const counters = Object.entries(counterHash!)
.sort(([, a], [, b]) => b - a) // sort desc
.reduce((r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v } }), {
total: 0,
regions: {},
})
return Response.json({ counters })
} catch (error) {
return Response.json({ error: error.message }, { status: 500 })
}
}),
}

本地运行 #

🌐 Run locally

supabase start
supabase 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

supabase functions deploy upstash-redis-counter --no-verify-jwt
supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env