0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Upstash Redisがめちゃ便利

0
Last updated at Posted at 2026-05-08

Redis使ってますか?
RDBのような永続的じゃないデータを扱う際に、非常に便利なインメモリで動くNOSQLのデータベースです。

そのRedisをHTTP接続で可能にする荷がUpstashです。

使用方法

ざっくりと使用する為のセットアップを記載します。

アカウント登録

まずはUpstashのアカウントを作成します。
上記のTOPページからStart For Freeで進めていきましょう。
Googleアカウントで作成可能です。

環境変数をコピー

作成後のConnectの項目に記載がある、以下の箇所をコピーします。

UPSTASH_REDIS_REST_URL="https://......
UPSTASH_REDIS_REST_TOKEN="********"

👆こちらは適切な値に変更してください。

npm install

Pythonなども可能ですが、今回はTypeScriptで試します。

yarn add @upstash/redis

サンプルコード

セットアップができたので、サンプルコードを載せてみます。

redis.ts
import { Redis } from '@upstash/redis';

class RedisUtility {
  private redis: Redis;
  constructor() {
    const {
      UPSTASH_REDIS_REST_URL,
      UPSTASH_REDIS_REST_TOKEN,
    } = process.env;

    // 先ほどコピーした環境変数をセットし、インスタンスを作成します。
    const redis = new Redis({
      url: UPSTASH_REDIS_REST_URL,
      token: UPSTASH_REDIS_REST_TOKEN,
    });
    this.redis = redis;
  }

  // 値のセット。exは有効期限です。適時変えちゃってください。
  async setRedis<T>(key: string, value: T) {
    return await this.redis.set(key, value, {
      ex: 60 * 10, // 10分後
    });
  }

  // 値は変えずに、時間を延長したい場合に使用します。
  async extension(key: string, second?: number) {
    await this.redis.expire(key, second ?? 60 * 10)
  }

  // 値を取得します。
  async getRedis<T>(key: string) {
    if (key == null || key === '') {
      throw new Error(`[Redis Util Error]指定したキーの取得に失敗しました。key: ${key}`);
    }
    const data = await this.redis.get<T>(key);
    return data;
  }
}
export { RedisUtility };

動かしてみた

値のセット

import { RedisUtility } from "@/lib/redis";

type DataType = {
 id: number;
 name: string;
 email: string;
}

const data = {
 id: 5656,
 name: 'Qiita',
 email: 'test-redis@example.com',
};
const redis = new RedisUtility();
await redis.setRedis(`${data.id}`, data);

値の取得

import { RedisUtility } from "@/lib/redis";

type DataType = {
 id: number;
 name: string;
 email: string;
}

const redis = new RedisUtility();
const data = await redis.getRedis<DataType>('5656');

/**
取得されたデータ
data = {
 id: 5656,
 name: 'Qiita',
 email: 'test-redis@example.com',
};
*

まとめ

気軽に使用できて制限つきですが、無料で使用できます!
ご覧の通り簡単なのでぜひみなさん使ってみてください!


オブジェクティブグループではXの投稿も平日毎日行っています!
IT 関連の小ネタや便利技から、日常のアニメ・ゲーム布教なども幅広く投稿してるので、
ご興味のある方は是非フォロー・いいねをお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?