Commit 8f896314 authored by 刘文胜's avatar 刘文胜

分享日志,声明式缓存工具类

parent 4589ac08
...@@ -292,16 +292,19 @@ function getWXV2(res, title, desc, link, imgUrl, mid,ent_code, id,type,forumThre ...@@ -292,16 +292,19 @@ function getWXV2(res, title, desc, link, imgUrl, mid,ent_code, id,type,forumThre
} }
//微信分享接口V2 //微信分享接口V2
router.get('/sharev2.js', function(req, res, next) { router.get('/sharev2.js', function(req, res, next) {
//记录分享日志
delete req.session.shareLog; //新的分享对象
var _v = new Date().getTime();//用于sharelog 版本号
var share_log = {_v:_v};
req.session.shareLog = {_v:_v};
var rs = {}, var rs = {},
type = req.query.type, type = req.query.type,
id = req.query.id, id = req.query.id,
uId= req.session.mobileForumUser.userId, uId= req.session.mobileForumUser.userId,
ent_code = req.session.user.ent_code, ent_code = req.session.user.ent_code,
mid = req.session.openUser.mid, mid = req.session.openUser.mid,
link = '/app/forum/' + ent_code + '/v2?pageUrl=', link = '/app/forum/' + ent_code + '/v2?pageUrl=';
share_log = {};
delete req.session.shareLog; //新的分享对象
var title = '',desc = '',imgUrl = ''; var title = '',desc = '',imgUrl = '';
...@@ -411,17 +414,18 @@ router.get('/sharev2.js', function(req, res, next) { ...@@ -411,17 +414,18 @@ router.get('/sharev2.js', function(req, res, next) {
}); });
}); });
}else if (type === 'Info') { }else if (type === 'Info') {
//分享记录对象
share_log.type = 2;
share_log.info = id;
//替换分享log内容
req.session.shareLog = share_log;
forumInfoService.getInfoById(id, function(err, forumInfo) { forumInfoService.getInfoById(id, function(err, forumInfo) {
if (err) { if (err) {
console.error(err); console.error(err);
res.json(_.assign({result:false},returnCode.BUSY)); res.json(_.assign({result:false},returnCode.BUSY));
}else{ }else{
//分享记录对象
share_log.type = 2;
share_log.info = id;
//替换分享log内容
if(req.session.shareLog._v === _v){
req.session.shareLog = share_log;
}
if(forumInfo.share_type && forumInfo.share_type == 1){ if(forumInfo.share_type && forumInfo.share_type == 1){
var shareInfo = forumInfo.share || {}; var shareInfo = forumInfo.share || {};
title = shareInfo.title,desc = shareInfo.description,imgUrl = shareInfo.icon; title = shareInfo.title,desc = shareInfo.description,imgUrl = shareInfo.icon;
...@@ -448,9 +452,9 @@ router.get('/sharev2.js', function(req, res, next) { ...@@ -448,9 +452,9 @@ router.get('/sharev2.js', function(req, res, next) {
share_log.info = thread.info._id || thread.info; share_log.info = thread.info._id || thread.info;
share_log.thread_type = thread.pid?4:thread.type; share_log.thread_type = thread.pid?4:thread.type;
//替换分享log内容 //替换分享log内容
if(req.session.shareLog._v === _v){
req.session.shareLog = share_log; req.session.shareLog = share_log;
}
//组装分享路径与判断分享类型 //组装分享路径与判断分享类型
var baseParamsUrl = '&infoId=' + thread.info._id + '&ent_code=' + ent_code + '&tId=' + thread._id +'&uId='+uId; var baseParamsUrl = '&infoId=' + thread.info._id + '&ent_code=' + ent_code + '&tId=' + thread._id +'&uId='+uId;
var share_type = ''; var share_type = '';
......
var cache = require('./cacheable');
var forumAboutMEService = require('../service/forumAboutMEService');
cache.cacheable(forumAboutMEService, 'me2other', { ns: 'forum.service.forumAboutMEService222', dur: 10000 });
//cache.clear(forumAboutMEService,'me2other','forum.service.forumAboutMEService222')
\ No newline at end of file
'use strict';
var _=require('lodash');
var async=require('async');
/**=====<1.缓存实现开始==========**/
function toCache(dur, k, v) {
if(v){
var str = '';
try{
str = JSON.stringify(v);
if(str){
redis.hset(dur.ns,k,str , function(err) {
redis.expire(k, dur.dur);
});
}
}catch(e){
console.log(e);
}
}
}
function fromCache(dur,k,cb){
redis.hget(dur.ns,k, function(err,v){
if(err){
return cb(err);
}
if(v){
var obj = null;
try{
obj = JSON.parse(v);
cb(null,obj);
}catch(e){
cb(e);
}
}else{
cb(null,null);
}
});
}
function loadAndCacheData(dur, key, fn, args, cb) {
var _cacheData = _.partial(toCache, dur, key);
//async.compose(_cacheData, fn).apply(null, args.concat(cb));相同实现
fn.apply(null,args.concat(function(){
var err = arguments[0];
var datas = Array.prototype.slice.call(arguments, 0);
if(!err){//缓存数据
_cacheData(datas);
}
//调用业务逻辑
cb.apply(null,datas);
}));
}
function getKey(ns, args) {
var key = Array.prototype.join.call(arguments,',');
return ns + ':' + key;
}
function withCache(dur, keyBuilder, fn) {
var args, cb, key;
args = Array.prototype.slice.call(arguments, 3, -1);
cb = _.last(arguments); // the callback function
key = keyBuilder.apply(null, [dur.ns].concat(args)); // compute cache key
fromCache(dur,key, function(err, datas) {
if (err) return cb(err);
if (datas) {// cache hit
console.log('cache hit');
cb.apply(null, datas);
}else {// cache missed
console.log('cache missed');
loadAndCacheData.call(null, dur, key, fn, args, cb);
}
});
}
function cacheable(fn,opts){
return _.partial(withCache, opts, getKey, fn);
}
/**=====缓存实现结束==========>**/
/**<=====2.清空缓存实现开始=============**/
function clear(ns){
redis.del(ns,function(err){
if(err){
console.log(err);
}
});
}
function withClear(ns, fn) {
var args = Array.prototype.slice.call(arguments, 2);
clear(ns);//先清缓存然后调用具体业务
fn.apply(null, args);
}
function clearable(fn,ns){
return _.partial(withClear, ns, fn);
}
/**=====清空缓存实现结束=============>**/
module.exports = {
/**
* 声明式缓存
* 使用方式:(前提是fn的最后一个参数是回调函数,回调函数第一个参数是err类似function(err,data1,data2,data3){})
* var cache = require('./cacheable');
* var service = require('../service/service1');
* cache.cacheable(service, 'method1', { ns: 'forum.service.service1', dur: 10000 });
* @param m :module对象
* @param fn :要缓存的函数名
* @param opts { ns: '', dur: 1000 }
* ns:缓存命名空间,dur:过期时间
*/
cacheable:function(m,fn,opts){
if(!m){
throw 'm 不能为空';
}
if(!fn){
throw 'fn 不能为空';
}
if(!m[fn]){
throw 'm 不存在fn函数';
}
if(!opts){
throw 'opts 不能为空';
}
if(!opts.ns){
throw 'opts.ns 不能为空';
}
if(!opts.dur || isNaN(opts.dur)){//默认缓存一小时
opts.dur = 1000 * 60 * 60;
}
m[fn] = cacheable(m[fn], opts);
},
/**
* 当调用某个方法时自动清空缓存
* 使用方式:
* var cache = require('./cacheable');
* var service = require('../service/service1');
* cache.clear(service, 'method1','forum.service.service1');
* @param m :module对象
* @param fn :函数名
* @param 缓存命名空间
*/
clear:function(m,fn,ns){
if(!m){
throw 'm 不能为空';
}
if(!fn){
throw 'fn 不能为空';
}
if(!m[fn]){
throw 'm 不存在fn函数';
}
if(!ns){
throw 'ns 不能为空';
}
m[fn] = clearable(m[fn], ns);
}
}
\ No newline at end of file
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