const DEFAULT_TTL = 60 * 1000; const MIN_10 = 1 * 60 * 1000; const cacheConfig = { '/api/page/index': DEFAULT_TTL, '/api/page/miner': DEFAULT_TTL, '/api/page/luck': DEFAULT_TTL, '/api/page/': DEFAULT_TTL, '/api/blocks': DEFAULT_TTL, '/api/miner/top10': MIN_10, '/api/block/history': MIN_10, '/api/pool/difficultyAvg': MIN_10, '/api/pool/hashrateAvg': MIN_10, }; function needCache(key) { return cacheConfig[key] || false; } /* * 接口 cache, 根据 url 前缀设置 cache * 开发环境不会启用缓存 */ module.exports = options => { const cachePrefix = 'page:'; return function* cache(next) { if (this.app.config.env !== 'prod' || this.request.query.refresh) { yield next; return; } const key = this.request.originalUrl; const url = key.indexOf('?') > 0 ? this.request.url.split('?')[0] : key; const ttl = needCache(url); if (!ttl) { yield next; } else { const data = yield this.app.redis.getAsync(cachePrefix + key); if (data) { this.logger.info('cached'); this.set('Cache-Control', `max-age=${ttl / 1000}`); this.response.body = data; return; } yield next; if (this.status === 200) { yield this.app.redis.setAsync(cachePrefix + key, JSON.stringify(this.response.body), 'EX', ttl / 1000); } } }; };