Skip to content

驗證別人 如何使用 PostgreSQL 取代 Redis 的教學

Published: at 下午05:41

前言

每周五都很期待看到 阮一峰 的科技愛好周刊

上週 在裡面看到一篇介紹 是說https://dev.to/polliog/i-replaced-redis-with-postgresql-and-its-faster-4942

感覺很有趣 以後就可以少準備一個 infra 了

把它紀錄 下來 總有一天會用到

實作 (接複製貼上 上面介紹的原文 若有)

創建一張快取表 (with UNLOGGED)

CREATE UNLOGGED TABLE cache (
  key TEXT PRIMARY KEY,
  value JSONB NOT NULL,
  expires_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX idx_cache_expires ON cache(expires_at);

寫入一筆資料

INSERT INTO cache (key, value, expires_at)
VALUES ($1, $2, NOW() + INTERVAL '1 hour')
ON CONFLICT (key) DO UPDATE
  SET value = EXCLUDED.value,
      expires_at = EXCLUDED.expires_at;