概述
本节继续优化 Nx 七牛云缓存插件的文件上传逻辑,调整 uploadToken 的更新策略,确保每次上传使用有效的 Token。同时验证公有空间和私有空间的下载兼容逻辑,确认完整的缓存读写流程正常工作。
技术要点
1. uploadToken 更新策略调整
优化 Token 获取逻辑,避免使用过期或无效的 Token:
class QiniuCacheHandler {
private uploadToken: string = ''
private tokenExpireAt: number = 0
/**
* 获取有效的 uploadToken
* 如果缓存的 Token 未过期则直接使用,否则重新生成
*/
async getValidToken(): Promise<string> {
if (this.uploadToken && Date.now() < this.tokenExpireAt) {
return this.uploadToken
}
// 重新生成 Token
this.uploadToken = await this.generateUploadToken()
// 提前 5 分钟过期
this.tokenExpireAt = Date.now() + 3600 * 1000 - 300 * 1000
return this.uploadToken
}
}
typescript
2. storeFile 上传优化
上传文件时使用缓存的 Token:
async storeFile(hash: string, cachePath: string): Promise<void> {
const token = await this.getValidToken()
const filename = this.getCacheFilename(hash)
await this.qiniuClient.upload(filename, cachePath, token)
}
typescript
3. 完整缓存流程验证
# 步骤一:首次构建(无缓存,执行完整构建并上传缓存)
npx nx reset
npx nx run-many -t build
# 观察日志:fileExists → false → storeFile → 上传成功
# 步骤二:清除本地缓存后重新构建(从远程拉取缓存)
npx nx reset
npx nx run-many -t build
# 观察日志:fileExists → true → retrieveFile → 下载成功
bash
4. 构建缓存生命周期
开发者 A 构建
|
├── 本地无缓存
├── 远程检查 fileExists(hash) → false
├── 执行完整构建
└── storeFile(hash, output) → 上传至七牛云
开发者 B 构建
|
├── 本地无缓存
├── 远程检查 fileExists(hash) → true
├── retrieveFile(hash) → 从七牛云下载
└── 跳过构建,使用缓存产物
text
扩展内容
Token 过期时间设计
// 建议 Token 有效期策略
const TOKEN_CONFIG = {
expiresIn: 3600, // 七牛云 Token 有效期(秒)
bufferTime: 300, // 提前过期缓冲时间(秒)
get actualExpireAt() {
return Date.now() + (this.expiresIn - this.bufferTime) * 1000
},
}
typescript
验证结果
# 完整验证流程
npx nx run-many -t build # 构建完成
npx nx reset # 重置
npx nx run-many -t build # 全部从缓存读取
# 日志输出示例:
# > NX Successfully ran target build for 5 projects
# >
# > Nx read the output from the cache for the following tasks:
# > - header:build
# > - components:build
# > - ...
bash
总结
uploadToken 更新策略通过缓存机制避免重复申请 Token,提前过期缓冲确保不会使用即将过期的凭证。配合 fileExists → retrieveFile → storeFile 的完整缓存读写流程,实现了 Nx 远程缓存在七牛云上的稳定运行。
↑