From 97db439f7c19474345ad8f9f66d591443cdc9e12 Mon Sep 17 00:00:00 2001 From: htoooth <ht.anglenx@gmail.com> Date: Tue, 29 Aug 2017 17:29:49 +0800 Subject: [PATCH] add cache --- apps/product/models/detail-product-api.js | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/apps/product/models/detail-product-api.js b/apps/product/models/detail-product-api.js index bab9303..a74721b 100644 --- a/apps/product/models/detail-product-api.js +++ b/apps/product/models/detail-product-api.js @@ -7,6 +7,43 @@ const api = global.yoho.API; const config = global.yoho.config; const redis = global.yoho.redis; +const cache = global.yoho.cache; +const logger = global.yoho.logger; +const uuid = require('uuid'); + +function _cacheGet(key) { + return cache.get(key).then((data) => { + if (data) { + return JSON.parse(data); + } + + return Promise.reject(); + }); +} + +// 半个月 +const HALF_MONTH = 60 * 60 * 24 * 15; + +function _cacheSave(key, value) { + return cache.set(key, value, HALF_MONTH) + .catch(err => logger.error(`save cache data fail:${err.toString()}`)); +} + +function _cached(fn, ctx) { + const pre = 'recommend-cache:' + (fn.name || 'random:' + uuid.v4()) + ':'; + + return function() { + const args = Array.prototype.slice.call(arguments); + const key = pre + JSON.stringify(args || '[]'); + + return _cacheGet(key).catch(() => { + return fn.apply(ctx, args).then(result => { + _cacheSave(key, result); + return result; + }); + }); + }; +} /** * 商品的 banner @@ -159,11 +196,11 @@ const getLikeAsync = (skn, limit) => { }; // 根据small_sort从redis获取分类下的关键词 -const getRecommendKeywords = (smallSort) => { +function _getRecommendKeywords(smallSort) { return redis.all([['get', `global:yoho:seo:keywords:sortId:${smallSort}:page:1`]]).then(res => { return res[0]; }); -}; +} module.exports = { getProductBannerAsync, @@ -177,5 +214,5 @@ module.exports = { getShopRecommendAsync, getBundleAsync, getLikeAsync, - getRecommendKeywords + getRecommendKeywords: _cached(_getRecommendKeywords) }; -- libgit2 0.24.0