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

สร้าง Real-Time Edge Leaderboard ด้วย Upstash Redis และ Fly.io

สร้าง Leaderboard ที่ Edge ด้วย Upstash Redis และ Fly.io

ในเว็บแอปพลิเคชันที่ไดนามิกและน่าสนใจ Leaderboards เป็นเครื่องมือทรงพลังสำหรับสร้างการแข่งขันและ engagement ของผู้ใช้ ในบทเรียนนี้ เราจะสร้าง real-time leaderboard ใช้ Upstash Redis เป็น backend storage และปรับใช้ที่ edge ด้วย Fly.io คู่นี้รวมประสิทธิภาพของ serverless Redis service กับ global distribution ของ Fly.io ให้ low-latency access สำหรับผู้ใช้ทั่วโลก

เกี่ยวกับ Upstash Redis

Upstash เป็น cloud service ให้ fully managed Redis service เน้น simplicity, scalability และ ease of use Redis ที่รู้จักใน versatility และ high-performance in-memory data store กลายเป็นน่าสนใจมากขึ้นเมื่อคู่กับ Upstash ด้วย Upstash นักพัฒนาสามารถ deploy และ scale Redis สำหรับ use cases ต่างๆ ได้อย่างราบรื่น โดยไม่มีความซับซ้อนด้าน infrastructure management

Key features ของ Upstash Redis:

  • Ease of Deployment: Upstash ลดความซับซ้อนการ deploy เหมาะสำหรับนักพัฒนาที่อยากลด operational complexities

  • High Performance: Redis เรียกข้อมูลได้เร็วมาก เหมาะสำหรับ task queuing, message passing, real-time leaderboards ด้วย Upstash scale อัตโนมัติตาม demand

  • Scalability: Redis scalable มาก และ Upstash scale auto ตาม demand ให้แอปพร้อมรับ varying loads

  • Data Store Integration: Redis ทำหน้าที่ message broker และ result store ลด components ที่ต้องจัดการ

ด้วยการนำ Upstash Redis มาใช้ใน real-time leaderboard เราใช้ประโยชน์จาก fully managed Redis service ที่เสริม global distribution ของ Fly.io ได้ architecture ที่ robust และ responsive

ข้อกำหนดเบื้องต้น

  • บัญชี Fly.io
  • ความรู้พื้นฐาน Flask และ Python

ตั้งค่าบัญชี Fly.io และ Redis Database

สร้างบัญชี Fly.io แล้วติดตั้ง Fly CLI:

# Linux
curl -L https://fly.io/install.sh | sh
# Other installation: https://fly.io/docs/hands-on/install-flyctl/

Login ด้วย Fly:

fly auth login

สร้าง Redis database สำหรับ leaderboard:

flyctl redis status upstash-fly-leaderboard
# หรือเปิด dashboard
fly redis dashboard 

ดึง private_url เก็บไว้สำหรับ Flask App

พัฒนา Flask Application

ใช้ Flask สร้าง leaderboard ติดตั้ง dependencies:

# flask - web framework
# redis - wrapper เชื่อม Redis
# gunicorn - wsgi server
$ pip install flask redis gunicorn
$ pip freeze > requirements.txt

สร้าง app.py:

import os
from flask import Flask, render_template, request, redirect, url_for
import redis

app = Flask(__name__)
UPSTASH_FLY_REDIS_CONNECTION_STRING = os.getenv('REDIS_URL')
LEADERBOARD_KEY = 'leaderboard'

redis_client = redis.from_url(UPSTASH_FLY_REDIS_CONNECTION_STRING)

ฟังก์ชันเพิ่ม score และดึง leaderboard:

def add_score(player_id, score):
  redis_client.zadd(LEADERBOARD_KEY, {player_id: score})

def get_leaderboard():
  leaderboard = redis_client.zrevrange(LEADERBOARD_KEY, 0, 9, withscores=True)
  formatted_leaderboard = [{'player_id': player_id.decode('utf-8'), 'score': int(score)} for player_id, score in leaderboard]
  return formatted_leaderboard

zadd เพิ่ม member พร้อม score ให้ sorted set zrevrange ดึง top 10 พร้อม scores

Endpoints

  • GET / — ดู leaderboard
  • POST /submit_score — ส่ง score
  • GET /clear_table — ล้าง leaderboard
@app.route('/')
def leaderboard():
  leaderboard = get_leaderboard()
  return render_template('leaderboard.html', leaderboard=leaderboard)

@app.route('/submit_score', methods=['POST'])
def submit_score():
  player_id = request.form['player_id']
  score = int(request.form['score'])
  add_score(player_id, score)
  return redirect(url_for('leaderboard'))

@app.route('/clear_table', methods=['GET'])
def clear_table():
  redis_client.delete(LEADERBOARD_KEY)
  return redirect(url_for('leaderboard'))

สร้าง templates/leaderboard.html สำหรับ frontend

ทดสอบ local:

# Linux
export REDIS_URL='YOUR_UPSTASH_FLY_REDIS_CONNECTION_STRING'
# Windows
set REDIS_URL='YOUR_UPSTASH_FLY_REDIS_CONNECTION_STRING'
$ flask run

ปรับใช้งานบน Fly.io

จาก root ของ codebase:

flyctl launch

จะ detect codebase สร้าง fly.toml และ Procfile:

app = "upstash-fly-leaderboard"
primary_region = "otp"
[env]
PORT = "8080"
[http_service]
internal_port = 8080
force_https = true
auto_stop_machines = true
auto_start_machines = true
min_machines_running = 0
processes = ["app"]
[[vm]]
cpu_kind = "shared"
cpus = 1
memory_mb = 1024

แก้ Procfile ให้รัน gunicorn port 8080:

web: gunicorn -b 0.0.0.0:8080 app:app

ตั้งค่า REDIS_URL เป็น secret ใน fly.io:

fly secrets set --app upstash-fly-leaderboard REDIS_URL=<>

Deploy:

fly deploy --ha=false

Output จะให้ URL ของแอปที่ deploy แล้ว

สรุป

ในบทเรียนนี้ เราเห็นการผสานรวม Upstash Redis และ Fly.io สร้าง real-time leaderboard รวมประสิทธิภาพ serverless Redis กับ global distribution ของ Fly.io ให้ low-latency access ทั่วโลก

สามารถขยายฟีเจอร์เพิ่มได้ เช่น user authentication, statistics เพิ่มเติม หรือฟีเจอร์อื่นๆ ที่เหมาะกับแอปของคุณ อนาคตของ engaging web applications อยู่ที่นี่ ขับเคลื่อนด้วย Upstash Redis และ global reach ของ Fly.io

Source code เต็มที่ GitHub: https://github.com/vjanz/upstash-fly-redis-leaderboard

หากมีคำถาม ติดต่อผมได้ หรือติดต่อ LinkedIn, GitHub

อ้างอิง

Upstash
https://redis.io
https://fly.io/