@ arkstack/ cache (帮助)
Arkstack 的缓存模块,为框架提供统一,基于驱动的缓存层.
存储
@arkstack/cache 箱外有四个仓库的船舶:
| 驱动程序 | 备份商店 | 页:1 |
|---|---|---|
memory | 正在处理 Map | 默认; 对 dev 和测试非常棒 |
file | 磁盘上的 JSON 文件 | 无需外部服务 |
redis | Redis( 通过 ioredis(中文(简体) ) | 分布式; 原子计数器 |
database | 通过表格 @arkstack/database | 重用您的数据库连接 |
配置
// src/config/cache.ts
import { Arkstack } from '@arkstack/contract'
import type { CacheConfig } from '@arkstack/cache'
import path from 'node:path'
export default (): CacheConfig => ({
default: env('CACHE_STORE', 'memory'),
prefix: env('CACHE_PREFIX', 'arkstack_cache_'),
stores: {
memory: { driver: 'memory' },
file: {
driver: 'file',
path: path.join(Arkstack.rootDir(), './storage/framework/cache'),
},
redis: {
driver: 'redis',
host: env('REDIS_HOST', '127.0.0.1'),
port: env('REDIS_PORT', 6379),
},
database: { driver: 'database', table: 'cache' },
},
})
使用量
import { Cache } from '@arkstack/cache'
// default store
await Cache.put('user:1', user, 60) // ttl in seconds
await Cache.get('user:1')
await Cache.forget('user:1')
// remember: read-through caching
const stats = await Cache.remember('stats', 300, () => computeStats())
// counters
await Cache.increment('hits')
await Cache.decrement('hits', 2)
// a specific store
await Cache.store('redis').forever('flag', true)
Ttl 接受数秒, a Date,或 null (永远).
自定义驱动程序
import { Cache, Store } from '@arkstack/cache'
class TagStore extends Store {
/* ... implement the Store contract ... */
}
Cache.extend('tags', (config) => new TagStore(config))
然后参考 { driver: 'tags' } 在商店配置.