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

สร้าง Next.js App ด้วย Serverless Cloud และ Upstash Redis - Quick Start Guide

Serverless Cloud เป็น Backend Platform จากทีมที่สร้าง Serverless Framework จ供给 Cloud Runtime, CLI และ SDK ในแพลตฟอร์มเดียวเพื่อเพิ่มประสิทธิภาพนักพัฒนา ในโพสต์นี้ เราจะสร้าง Next.js Application ที่อ่านข้อมูลจาก Serverless Redis (Upstash) และ Deploy ไปที่ Serverless Cloud

Setup

เริ่มต้น Serverless Cloud ด้วย: npm init cloud

? Do you want to create a new app or work on an existing one? ℹ You've selected Create new app.
? Please choose an app template to generate in this directory. ℹ You've selected Next.js.
? Please enter a name for your app. ℹ You've entered serverless-cloud.

เลือก Next.js เป็น Template เพื่อสร้าง Next.js Project ใหม่

ในโฟลเดอร์โปรเจกต์ ติดตั้ง Upstash Redis Client: npm install @upstash/redis

สร้าง Redis Database ผ่าน Upstash Console ใช้ CLI Insert ข้อมูล users ดังนี้:

set users '[{ "id": "12", "name": "John Doe"}, { "id": "13", "name": "Jane Smith"}]'

สร้าง Next.js App ด้วย Serverless Cloud และ Upstash Redis - Quick Start Guide

อัปเดต user.js แทนที่ Upstash REST URL และ Token:

// user.js - Next.js API route
import { Redis } from "@upstash/redis";

const redis = new Redis({
    url: "REPLACE_HERE",
    token: "REPLACE_HERE",
});

export default async function handler(req, res) {
    const data = await redis.get("users");
    res.status(200).json({ users: data });
}

Test และ Deploy

ใน Serverless Cloud Interactive CLI รัน dev ควรเห็นหน้าตาประมาณนี้ที่ https://localhost:3000/:

สร้าง Next.js App ด้วย Serverless Cloud และ Upstash Redis - Quick Start Guide

เห็น Users ที่เก็บใน Redis แสดงออกมา

Deploy Application ไป Cloud ด้วยคำสั่ง: deploy dev ใน Interactive CLI ตรวจสอบ Metrics และ Application Logs ได้ที่ Serverless Cloud Dashboard

สร้าง Next.js App ด้วย Serverless Cloud และ Upstash Redis - Quick Start Guide

ข้อสรุป

ในโพสต์นี้ เราสร้าง Next.js Application บน Serverless Cloud และใช้ Upstash Redis เป็น Data Store

ติดตามเราที่ Discord และ Twitter