Commit 2005bb33 authored by 姜登's avatar 姜登

redis

parent 60814cd2
Pipeline #21937 passed with stage
in 2 seconds
......@@ -17,11 +17,7 @@ class Cache {
if (data) {
return data;
}
if (next instanceof Promise) {
data = await next;
} else {
data = await next(key);
}
data = await next(key);
await this.set(key, data, ttl);
return data;
}
......@@ -44,18 +40,9 @@ class Cache {
this.app.logger.info(`[cache](${+new Date() - startTime}ms) ${this.name}.${key}: ${jsonText}`);
return ret;
}
async set(key, value, ttl = 60) {
return await this._set(key, value, ttl);
}
async ttl(key) {
return await this._ttl(key);
}
async lock(key, ttl, fn) {
return await this._lock(key, ttl, fn);
}
}
class RedisCacheWrap extends Cache {
......@@ -63,10 +50,6 @@ class RedisCacheWrap extends Cache {
super(app);
this.redis = redis;
this.name = 'redis-cache';
redis.defineCommand('lock', {
numberOfKeys: 1,
lua: 'return redis.call("set", KEYS[1], ARGV[1], "NX", "EX", ARGV[2])',
});
}
async _get(key) {
......@@ -89,40 +72,6 @@ class RedisCacheWrap extends Cache {
await redis.set(key, value);
}
}
async _ttl(key) {
const { redis } = this;
const r = await redis.ttl(key);
return r < 0 ? undefined : r;
}
async _lock(key, ttl, fn) {
const { app, redis } = this;
const redisLockName = app.name + '/' + app.config.env + '/lock/' + key;
// 获取当前时间秒和截止时间
const currentTime = Math.round(new Date().getTime() / 1000);
const expireTime = +ttl + currentTime;
// 加锁lua脚本,key存在返回null,不存在则设置key-value并返回OK
const lock = await redis.lock(redisLockName, expireTime, ttl);
if (!lock) {
// 如存在锁判断是否超时
const preLockTime = +await redis.get(redisLockName);
if (preLockTime > currentTime) {
throw Error('系统繁忙,请稍后再试!');
}
// 原子方法getset,重新设置值,并返回之前设置的值
// 如超时重新设置value,并再次判断是否有其他进程获取到锁
const resetLockTime = +await redis.getset(redisLockName, expireTime);
if (resetLockTime !== preLockTime) {
throw Error('系统繁忙,请稍后重试!');// 表示有其他进程获取到锁
}
}
// 执行fn逻辑并删除锁
try {
return await fn.apply(this, []);
} finally {
await redis.del(redisLockName);
}
}
}
class NodeCacheWrap extends Cache {
......@@ -144,9 +93,6 @@ class NodeCacheWrap extends Cache {
cache.set(key, value);
}
}
async _ttl(key) {
return this.cache.getTtl(key);
}
}
module.exports = {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment