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?

(Node.js) NodeCacheモジュールを理解する

Posted at

はじめに

node.jsのコードの中で NodeCacheモジュールを使用する機会があったので、どのようなモジュールであるのか簡単にまとめたいと思います。

NodeCacheモジュールとは

NodeCache は、Node.js アプリケーション内で手軽に使える インメモリ(メモリ常駐)型のキー・バリューキャッシュ ライブラリです。Redis などの外部ミドルウェアを立てずに “ちょっとしたキャッシュ” を実装したい場面で便利に使用できます。
トークンやセッション情報の短期保存をし、 同一リクエストの重複呼び出しを防ぎます。

基本的な使い方

cacheTest.js
/**
 * cacheTest.js
 * NodeCache の基本操作 & TTL 検証デモ
 */

// インストール済みでなければ:  npm install node-cache
const NodeCache = require("node-cache");

// 1. キャッシュ生成(TTL 30 秒)
const cache = new NodeCache({ stdTTL: 30, checkperiod: 30 });
// stdTTL: 30  追加した要素のデフォルト生存時間を 30秒 に設定。
// checkperiod: 30  30秒ごとに期限切れ要素を掃除。

// 2. サンプルデータ
const key = "sample-token";
const value = { user: "Alice", role: "admin" };

// 3. set で保存
cache.set(key, value); // TTL = 30 秒
console.log("[0s] set 完了");

// 4. 直後に has / get
console.log("[0s] has  →", cache.has(key)); // true
console.log("[0s] get  →", cache.get(key)); // { user: 'Alice', role: 'admin' }

// 5. 31 秒後に再チェック(TTL 超過)
setTimeout(() => {
  console.log("\n[31s] --- TTL 30 秒を経過 ---");
  console.log("[31s] has →", cache.has(key)); // false
  console.log("[31s] get →", cache.get(key)); // undefined
}, 31 * 1000);

has(key)の返り値は、true / falseです。
キーがキャッシュに存在するかだけ調べます。

get(key)の返り値は、値または undefinedです。
実際の値を取得(期限切れなら undefined)します。

以下がコンソールに出力されます。

[0s] set 完了
[0s] has → true
[0s] get → { user: 'Alice', role: 'admin' }

[31s] --- TTL 30 秒を経過 ---
[31s] has → false
[31s] get → undefined

期限である30秒を過ぎたらキャッシュが自動で消え、has は false、get は undefined になることを確認できます。

まとめ

NodeCacheモジュールの基本的な使い方についてまとめました。

Reference

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?