Authored by 周少峰

Merge branch 'hotfix/add-cache' into gray

@@ -7,6 +7,43 @@ @@ -7,6 +7,43 @@
7 const api = global.yoho.API; 7 const api = global.yoho.API;
8 const config = global.yoho.config; 8 const config = global.yoho.config;
9 const redis = global.yoho.redis; 9 const redis = global.yoho.redis;
  10 +const cache = global.yoho.cache;
  11 +const logger = global.yoho.logger;
  12 +const uuid = require('uuid');
  13 +
  14 +function _cacheGet(key) {
  15 + return cache.get(key).then((data) => {
  16 + if (data) {
  17 + return JSON.parse(data);
  18 + }
  19 +
  20 + return Promise.reject();
  21 + });
  22 +}
  23 +
  24 +// 半个月
  25 +const HALF_MONTH = 60 * 60 * 24 * 15;
  26 +
  27 +function _cacheSave(key, value) {
  28 + return cache.set(key, value, HALF_MONTH)
  29 + .catch(err => logger.error(`save cache data fail:${err.toString()}`));
  30 +}
  31 +
  32 +function _cached(fn, ctx) {
  33 + const pre = 'recommend-cache:' + (fn.name || 'random:' + uuid.v4()) + ':';
  34 +
  35 + return function() {
  36 + const args = Array.prototype.slice.call(arguments);
  37 + const key = pre + JSON.stringify(args || '[]');
  38 +
  39 + return _cacheGet(key).catch(() => {
  40 + return fn.apply(ctx, args).then(result => {
  41 + _cacheSave(key, result);
  42 + return result;
  43 + });
  44 + });
  45 + };
  46 +}
10 47
11 /** 48 /**
12 * 商品的 banner 49 * 商品的 banner
@@ -159,11 +196,11 @@ const getLikeAsync = (skn, limit) => { @@ -159,11 +196,11 @@ const getLikeAsync = (skn, limit) => {
159 }; 196 };
160 197
161 // 根据small_sort从redis获取分类下的关键词 198 // 根据small_sort从redis获取分类下的关键词
162 -const getRecommendKeywords = (smallSort) => { 199 +function _getRecommendKeywords(smallSort) {
163 return redis.all([['get', `global:yoho:seo:keywords:sortId:${smallSort}:page:1`]]).then(res => { 200 return redis.all([['get', `global:yoho:seo:keywords:sortId:${smallSort}:page:1`]]).then(res => {
164 return res[0]; 201 return res[0];
165 }); 202 });
166 -}; 203 +}
167 204
168 module.exports = { 205 module.exports = {
169 getProductBannerAsync, 206 getProductBannerAsync,
@@ -177,5 +214,5 @@ module.exports = { @@ -177,5 +214,5 @@ module.exports = {
177 getShopRecommendAsync, 214 getShopRecommendAsync,
178 getBundleAsync, 215 getBundleAsync,
179 getLikeAsync, 216 getLikeAsync,
180 - getRecommendKeywords 217 + getRecommendKeywords: _cached(_getRecommendKeywords)
181 }; 218 };