npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kne/fastify-kv-cache

v0.1.0

Published

Fastify 键值缓存插件,支持 Redis、PostgreSQL 及混合模式,提供高性能热冷数据分层存储。

Downloads

62

Readme

fastify-kv-cache

描述

Fastify 键值缓存插件,支持 Redis、PostgreSQL 及混合模式,提供高性能热冷数据分层存储。

安装

npm i --save @kne/fastify-kv-cache

概述

项目概述

@kne/fastify-kv-cache 是一个高性能的 Fastify 键值缓存插件,支持 Redis、PostgreSQL 及混合模式,提供热冷数据分层存储能力。

主要特性

  • 多模式存储:支持 redis(纯热缓存)、pg(纯冷存储)、hybrid(热冷分层)三种模式
  • 热冷分层:混合模式下 Redis 作为热数据层,PostgreSQL 作为冷数据层,读取时自动回写热缓存
  • TTL 过期:支持设置键值过期时间,Redis 和 PostgreSQL 均支持
  • 容量管理:PostgreSQL 模式下支持 pgMaxSize 容量限制,自动清理最旧数据
  • 命名空间隔离:支持多命名空间,避免不同业务间的键冲突
  • 访问计数:PostgreSQL 模式下自动记录键的访问次数(hits)
  • 数据库初始化:提供 initSQLgetInitSQLinitDatabase 方法,便捷完成表结构创建

使用场景

  • 会话(Session)数据缓存
  • API 响应结果缓存
  • 热点数据加速访问
  • 临时凭证 / Token 管理
  • 分布式锁实现
  • 需要持久化的键值存储

示例

API

插件注册

const fastify = require('fastify')();
const kvCachePlugin = require('@kne/fastify-kv-cache');

await fastify.register(kvCachePlugin, {
  mode: 'redis',
  redis: { host: '127.0.0.1', port: 6379 }
});

await fastify.ready();
// 通过 fastify.KVCache 访问缓存实例

注册参数

| 参数名 | 类型 | 必填 | 默认值 | 说明 | |--------|------|------|--------|------| | mode | string | 是 | - | 缓存模式:redispghybrid | | namespace | string | 否 | default | 命名空间,用于隔离不同用途的缓存 | | redis | object | mode 为 redis/hybrid 时必填 | - | Redis 连接配置(ioredis 格式) | | pg | object | mode 为 pg/hybrid 时必填 | - | PostgreSQL 连接配置(pg.Pool 格式) | | hybrid | object | 否 | - | 混合模式配置,详见 Hybrid 配置 | | name | string | 否 | KVCache | 装饰器名称标识 | | dbTableName | string | 否 | kv_cache | PostgreSQL 表名(不含前缀) | | dbTableNamePrefix | string | 否 | t_ | PostgreSQL 表名前缀 |

Redis 配置

传入 redis 参数时使用 ioredis 连接配置格式:

| 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | host | string | 是 | Redis 主机地址 | | port | number | 否 | Redis 端口,默认 6379 | | password | string | 否 | Redis 密码 | | db | number | 否 | Redis 数据库编号 |

PostgreSQL 配置

传入 pg 参数时使用 pg.Pool 连接配置格式:

| 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | host | string | 是 | PostgreSQL 主机地址 | | port | number | 否 | PostgreSQL 端口,默认 5432 | | user | string | 是 | 数据库用户名 | | password | string | 是 | 数据库密码 | | database | string | 是 | 数据库名称 |

Hybrid 配置

modehybrid 时,通过 hybrid 对象配置混合模式行为:

| 参数名 | 类型 | 必填 | 说明 | |--------|------|------|------| | redisTTL | number | 否 | 从 PostgreSQL 回写 Redis 时的过期时间(秒),设置后读取冷数据会自动回写热缓存 | | pgMaxSize | number | 否 | PostgreSQL 命名空间最大存储容量(字节),超限后自动按 updated_at 清理最旧数据 |

KVCache 实例方法

插件注册后,通过 fastify.KVCache 访问缓存实例。

get(key)

获取缓存值。根据模式不同,读取逻辑如下:

| 模式 | 行为 | |------|------| | redis | 从 Redis 读取 | | pg | 从 PostgreSQL 读取 | | hybrid | 优先从 Redis 读取;若 Redis 未命中,从 PostgreSQL 读取;若设置了 hybrid.redisTTL,将冷数据回写至 Redis |

| 参数 | 类型 | 说明 | |------|------|------| | key | string | 缓存键 |

返回值: 缓存值(JSON 解析后的对象),未找到返回 null

set(key, value, ttl)

设置缓存值。

| 参数 | 类型 | 必填 | 说明 | |------|------|------|------| | key | string | 是 | 缓存键 | | value | any | 是 | 缓存值(自动 JSON 序列化) | | ttl | number | 否 | 过期时间(秒),不设置则永不过期 |

行为

  • hybrid 模式下同时写入 Redis 和 PostgreSQL
  • redis 模式下仅写入 Redis
  • pg 模式下仅写入 PostgreSQL

返回值: 无

del(key)

删除缓存。使用 Promise.allSettled 并行删除所有可用后端,不会因某个后端删除失败而中断。

| 参数 | 类型 | 必填 | 说明 | |------|------|------|------| | key | string | 是 | 缓存键 |

返回值: 无

静态属性与方法

除了实例方法外,fastify.KVCache 还提供以下静态属性:

| 属性/方法 | 类型 | 说明 | |-----------|------|------| | initSQL | string | 当前表名的初始化 SQL 语句(默认表名 t_kv_cache) | | getInitSQL | function | getInitSQL(tableName) 生成指定表名的初始化 SQL | | initDatabase | function | initDatabase(pool, tableName) 执行初始化 SQL 创建表 |

使用示例

const { Pool } = require('pg');
const pool = new Pool(pgConfig);

// 方式一:使用 initSQL(使用注册时的表名)
await pool.query(fastify.KVCache.initSQL);

// 方式二:使用 getInitSQL(自定义表名)
await pool.query(fastify.KVCache.getInitSQL('custom_table'));

// 方式三:使用 initDatabase(自动执行 SQL)
await fastify.KVCache.initDatabase(pool, 'custom_table');

数据库初始化

使用 PostgreSQL 或混合模式时,需先执行初始化 SQL 创建表结构:

const kvCachePlugin = require('@kne/fastify-kv-cache');

// 注册插件后使用 initDatabase
await fastify.register(kvCachePlugin, {
  mode: 'pg',
  pg: { host: '127.0.0.1', user: 'postgres', password: '123456', database: 'test' }
});
await fastify.ready();

const { Pool } = require('pg');
const pool = new Pool({ host: '127.0.0.1', user: 'postgres', password: '123456', database: 'test' });
await fastify.KVCache.initDatabase(pool);

初始化 SQL

默认表名 t_kv_cache 对应的 SQL:

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE UNLOGGED TABLE IF NOT EXISTS t_kv_cache (
  namespace   TEXT NOT NULL,
  key         TEXT NOT NULL,
  value       JSONB NOT NULL,
  size        INT NOT NULL,
  hits        INT DEFAULT 0,
  expires_at  TIMESTAMP,
  updated_at  TIMESTAMP DEFAULT now(),
  PRIMARY KEY (namespace, key)
);

CREATE INDEX IF NOT EXISTS idx_t_kv_cache_updated
ON t_kv_cache (namespace, updated_at);

存储结构

Redis 键格式

{namespace}:{key}

值以 JSON 字符串存储,读取时自动 JSON.parse 解析。

PostgreSQL 表结构

| 字段 | 类型 | 说明 | |------|------|------| | namespace | TEXT | 命名空间 | | key | TEXT | 缓存键 | | value | JSONB | 缓存值(JSON 序列化存储) | | size | INT | 值大小(字节) | | hits | INT | 访问次数,每次 get 自动 +1 | | expires_at | TIMESTAMP | 过期时间,为 NULL 表示永不过期 | | updated_at | TIMESTAMP | 更新时间,自动更新 |