Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Redis

เชื่อม Upstash Redis กับ Cloudflare Workers อย่างง่าย: สร้าง URL Shortener แบบ Serverless

Cloudflare Release Upstash Integration สำหรับ Cloudflare Workers ทำให้ใช้ Upstash Products บน Workers ง่ายขึ้น Blog Post นี้ใช้ Upstash Redis Integration สร้าง URL Shortener แบบ Serverless

Getting Started - เริ่มต้น

Steps สร้างโปรเจกต์:

  • Set up Upstash Database
  • Create Worker บน Cloudflare
  • Integrate Cloudflare Workers กับ Upstash
  • Implement Project Algorithm
  • Deploy Application

Creating the Database - สร้าง Database

ไป Upstash Console สร้าง Redis Database กด Create database ใน Section Redis

เชื่อม Upstash Redis กับ Cloudflare Workers อย่างง่าย: สร้าง URL Shortener แบบ Serverless

Database พร้อมใช้งาน!

Creating the Cloudflare Worker - สร้าง Cloudflare Worker

ใช้ Cloudflare CLI Tool Generate Worker เปิด Terminal รัน:

npm create cloudflare@latest

Command นี้ Walkthrough Options/Configs สุดท้าย Request Login Cloudflare ตัวอย่าง Config และ Output:

สร้างและ Deploy App ด้วย Single Command Initialize Folder แบบนี้:

/url-shortener
src
└── worker.ts
node_modules
package-lock.json
package.json
tsconfig.json
wrangler.toml

Enable Upstash Integration ง่ายเท่ากัน

Cloudflare - Upstash Integration

เข้า Cloudflare Dashboard Login Account เดียวกับที่สร้าง url-shortener ไป Workers & Pages > Overview Sidebar จะเจอ url-shortener App

เชื่อม Upstash Redis กับ Cloudflare Workers อย่างง่าย: สร้าง URL Shortener แบบ Serverless

Click App → Application Details Page ทำ Integration Switch Tab Settings ไป Integrations Section เห็น Worker Integrations กด Add Integration ของ Upstash Redis

เชื่อม Upstash Redis กับ Cloudflare Workers อย่างง่าย: สร้าง URL Shortener แบบ Serverless

Integration Page Connect Upstash Account เลือก Database url-shortener จาก Dropdown กด Save button

Note: อย่าเปลี่ยน Secret Names ขั้น Configure secrets Credentials จะ Auto-picked Up โดย Redis.fromEnv(env) เป็น UPSTASH_REDIS_REST_URL และ UPSTASH_REDIS_REST_TOKEN

เชื่อม Upstash Redis กับ Cloudflare Workers อย่างง่าย: สร้าง URL Shortener แบบ Serverless

Implementing URL Shortener - Implement URL Shortener

Implementation เรียบง่าย 2 Functions:

  • POST URL → Generate Random Key Assign ให้ URL Key-URL Pair Store ใน Redis ส่ง Key Appended as Path ให้ User Format <YOUR_WORKER_URL>/<KEY>
  • User Access Worker URL พร้อม Key ที่ Add ไว้ → Retrieve Value จาก Redis Redirect ไป URL ด้วย 307 Response Code

Implement ใน src/worker.ts Basic Implementation:

import { Redis } from "@upstash/redis/cloudflare";
export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; }
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const redis = Redis.fromEnv(env);
    async function generateRandomKey(): Promise<string> {
      const key: string = btoa(crypto.getRandomValues(new Uint8Array(2)).toString()).replaceAll("=", "");
      if (await redis.exists(key)) { return generateRandomKey(); }
      return key;
    }
    if (request.method === "POST") {
      const requestUrl = request.url;
      const body = await request.text();
      const { longUrl } = JSON.parse(body);
      const key = await generateRandomKey();
      redis.set(key, longUrl);
      const responseUrl = requestUrl + key;
      return new Response(responseUrl);
    }
    const slug: string = request.url.split("/").pop() || "";
    const url = (await redis.get(slug)) as string;
    if (url) { return Response.redirect(url, 307); }
    else { const errorText = !slug ? "Please provide a slug." : `Slug ${slug} not found. `; return new Response(errorText, { status: 404 }); }
  },
};

Algorithm Ready Deploy App ไป Terminal url-shortener Folder รัน:

npm run deploy

Cloudflare Worker Up และ Running! Test ได้ใน App Dashboard หรือ curl ตัวอย่าง Request:

curl -X POST https://url-shortener.fahreddin.workers.dev \
  -d '{ "longUrl" : "https://google.com" }'

Click Response URL Redirect ไป https://google.com

Conclusion - สรุป

ขอบคุณที่ติดตาม!

คุณค้นพบว่า Serverless Functions + Upstash Redis เปิดโอกาสมากมายสำหรับ Projects Versatility และ Efficiency ของคู่นี้ Empower คุณสร้าง Solutions ที่ Innovative และ Responsive

Guide นี้แค่ต้นเริ่ม ไม่มี Limit ในการ Expand และ Improve Project

คำถาม/ปัญหา ติดต่อ fahreddin@upstash.com

Happy Coding!