Commit f98c12e2 by liimin

优化缓存逻辑

1 parent 05572363
......@@ -8,6 +8,7 @@ const path = require('path');
class AppBootHook {
constructor(app) {
this.app = app;
this.helper = app.helper;
}
async configWillLoad() {
console.log(`
......@@ -25,9 +26,23 @@ const path = require('path');
async didReady() {
// 应用已经启动完毕
// 加载所有的校验规则
console.log('================加载所有的校验规则================')
console.log('================加载校验规则================')
const directory = path.join(this.app.config.baseDir, './app/validate');
this.app.loader.loadToApp(directory, 'validate');
console.log('================重置时间对象================')
const ctx = await this.app.createAnonymousContext();
const { service, helper } = ctx;
const { date, constant, moment } = helper
const yesterday = date(-1);
const today = date(0);
var { init_date, cache_update_time_diff } = this.app.config.sys;
await service.cache.set(constant.DATES,{
today,
yesterday,
cache_data_last_date:init_date,
cache_update_time:moment().subtract(cache_update_time_diff +1 ,'milliseconds'),
});
}
}
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:20:01
* @Last Modified by: limin
* @Last Modified time: 2019-12-04 17:59:15
* @Last Modified time: 2019-12-05 17:26:22
*/
"use strict";
......@@ -28,7 +28,7 @@ class UserController extends Controller {
/**
* 从内存获取日期(昨天,今天)
*/
async _fetch_date_in_cache(){
async _fetch_date_in_cache_(){
const { DATES } = this.helper.constant;
return await this.CacheService.get(DATES);
}
......@@ -37,15 +37,13 @@ class UserController extends Controller {
* 对比和获取内存中的数据(总共30天,每天通过定时任务更新)
* 如果获取的时候数据还是最新则手动触发定时任务更新一次
*/
async _compare_get(){
const { USER_SUMMARY_30_DAY } = this.helper.constant;
var summary_30_day = await this.CacheService.get(USER_SUMMARY_30_DAY);
var { date } = summary_30_day;
var { yesterday } = await this._fetch_date_in_cache();
if(!this.helper.moment(date).isSame(yesterday)){ //如果 内存中的数据的日期不是昨天的 则手动启动定时器 更新缓存数据
async _compare_get_(isRunTask){
var { yesterday, cache_data_last_date } = await this._fetch_date_in_cache_();
if(!this.helper.moment(cache_data_last_date).isSame(yesterday) && isRunTask){ //如果 内存中的数据的日期不是昨天的 则手动启动定时器 更新缓存数据
await this.app.runSchedule('update_cache');
summary_30_day = await this.CacheService.get(USER_SUMMARY_30_DAY);
}
const { USER_SUMMARY_30_DAY } = this.helper.constant;
const summary_30_day = await this.CacheService.get(USER_SUMMARY_30_DAY);
return summary_30_day
}
......@@ -53,13 +51,14 @@ class UserController extends Controller {
* 内部方法 从内存获取 昨天的统计数据
* 比较数据时间 如果不是昨天的数据 则启动定时任务 更新一遍数据 再次获取数据并返回
*/
async _fetch_summary( { beginDate,endDate,isGetLast }, fn ){
var summary_30_day= await this._compare_get();
async _fetch_summary_( { beginDate,endDate,isGetLast }, fn ){
var summary_30_day= await this._compare_get_(isGetLast);
const { moment } =this.helper
var result=[];
if(isGetLast){
result = summary_30_day[date];
fn && fn(date,summary_30_day[date])
const { cache_data_last_date } = await this._fetch_date_in_cache_();;
result = summary_30_day[cache_data_last_date];
fn && fn(cache_data_last_date,summary_30_day[cache_data_last_date])
}else if(beginDate){
endDate = endDate || beginDate;
if(moment(beginDate).isSame(endDate) ){
......@@ -67,7 +66,6 @@ class UserController extends Controller {
fn && fn(beginDate,summary_30_day[beginDate])
}else{
for(const day in summary_30_day){
if(day ==='date') continue;
if(moment(day).isBetween(beginDate,endDate)
|| moment(day).isSame(beginDate)
|| moment(day).isSame(endDate)){
......@@ -77,7 +75,6 @@ class UserController extends Controller {
}
}
}else{
delete summary_30_day.date
if(fn){
for(const day in summary_30_day){
fn(day,summary_30_day[day])
......@@ -93,7 +90,7 @@ class UserController extends Controller {
* @param {*} obj
* @param {*} field
*/
_reduce(obj,field){
_reduce_(obj,field){
return obj.reduce((pre,next)=>pre + +next[field],0)
}
/**
......@@ -101,7 +98,7 @@ class UserController extends Controller {
* @param {*} field
* @param {*} fn
*/
async _set(field,fn){
async _set_(field,fn){
var total;
if(typeof field ==='string'){
total = await fn(field)
......@@ -117,15 +114,15 @@ class UserController extends Controller {
/**
* 内部方法 从内存获取 最后一天的统计数据
*/
async _fetch_total_last_day({ pid, cid , field } ){
const _summary = await this._fetch_summary({isGetLast:true});
async _fetch_total_last_day_({ pid, cid , field } ){
const _summary = await this._fetch_summary_({isGetLast:true});
var { p } =_summary;
var total= 0;
if (pid) {
var obj = cid ? p[pid]["c"][cid] : p[pid];
obj && (total =await this._set(field,async f=>obj[f]));
obj && (total =await this._set_(field,async f=>obj[f]));
}else{
total =await this._set(field,async f=>_summary[f])
total =await this._set_(field,async f=>_summary[f])
}
return total;
}
......@@ -134,9 +131,9 @@ class UserController extends Controller {
/**
* 内部方法 从内存获取 范围时间内的数据
*/
async _fetch_total_by_range({ pid, cid , field, beginDate,endDate } ){
async _fetch_total_by_range_({ pid, cid , field, beginDate,endDate } ){
var res = []
const _list = await this._fetch_summary({ beginDate, endDate });
const _list = await this._fetch_summary_({ beginDate, endDate });
if( _list && _list.length ){
var fn = null;
var num=0;
......@@ -158,7 +155,7 @@ class UserController extends Controller {
return pre+num
},0)
}
res = await this._set(field,fn)
res = await this._set_(field,fn)
}
return res;
}
......@@ -166,11 +163,11 @@ class UserController extends Controller {
/**
* 内部方法 从内存获取 范围时间内的数据
*/
async _fetch_detail_by_range({ pid, cid , field, beginDate,endDate } ){
async _fetch_detail_by_range_({ pid, cid , field, beginDate,endDate } ){
var res = []
var _set = this._set
var _set = this._set_
var data = null
await this._fetch_summary({ beginDate, endDate },async (day,value)=>{
await this._fetch_summary_({ beginDate, endDate },async (day,value)=>{
var fn = null;
if (pid) {
if(cid){
......@@ -192,9 +189,9 @@ class UserController extends Controller {
* @Request query integer pid 省份id
*/
async total({ query: { pid,cid } }) {
var total = await this._fetch_total_last_day({ pid,cid,field:'u'})
var total = await this._fetch_total_last_day_({ pid,cid,field:'u'})
const realtime = await this.UserService.user_realtime({ pid, cid });
const realtime_total = this._reduce(realtime,'increase');
const realtime_total = this._reduce_(realtime,'increase');
total += ~~realtime_total;
const data = { total };
this.ctx.body = this.ServerResponse.Success(data);
......@@ -205,27 +202,26 @@ class UserController extends Controller {
* @Request query integer pid 省份id
*/
async statistics({ query: { pid,cid } }) {
const beginDate7 = this.helper.date(-7,'YYYYMMDD');
const { yesterday } = await this._fetch_date_in_cache();
var { r, u } = await this._fetch_total_last_day_({ pid,cid,field:['r','u']});
// 昨天的付费转化率 (昨天的付费总人数 / 昨天用户总数)
const renew = this.helper.percent(r,u);
const beginDate7 = this.helper.date(-7);
const { yesterday } = await this._fetch_date_in_cache_();
//近7天所有
const { i:increased7,a:nLive7 } = await this._fetch_total_by_range({ pid, cid, field:['i','a'],beginDate:beginDate7,endDate:yesterday});
const { i:increased7,a:nLive7 } = await this._fetch_total_by_range_({ pid, cid, field:['i','a'],beginDate:beginDate7,endDate:yesterday});
// 近七天 用户活跃度 (近7天 活跃用户数 / 近7天新增用户数)
const live7 = this.helper.percent(nLive7,increased7);
//近30天所有
const { i:increased30,a:nLive30 } = await this._fetch_total_by_range({ pid, cid, field:['i','a']});
const { i:increased30,a:nLive30 } = await this._fetch_total_by_range_({ pid, cid, field:['i','a']});
// 近30天 用户活跃度 (近30天 活跃用户数 / 近30天新增用户数)
const live30 = this.helper.percent(nLive30,increased30);
var { r, u } = await this._fetch_total_last_day({ pid,cid,field:['r','u']});
// 昨天的付费转化率 (昨天的付费总人数 / 昨天用户总数)
const renew = this.helper.percent(r,u);
const data = { increased7, live7,increased30,live30,renew };
this.ctx.body = this.ServerResponse.Success(data);
}
/**
* @Router GET /screen/user/gender
* @Description 数据大屏-用户性别、年龄段、以及数量的占比
* @Description 数据大屏-用户性别、年龄段、以及数量的占比 2: 00后,3: 90后,4: 80后,5: 70后,6: 60后,7:其他
* @Request query integer pid 省份id
* @Request query integer cid 城市id
*/
......@@ -274,7 +270,7 @@ class UserController extends Controller {
* @Description 数据大屏-1 用户新增趋势 2.用户活跃趋势, 3.用户付费趋势 4.用户车辆出行趋势
* @Request query integer pid 省份id
* @Request query integer cid 城市id
* @Request query string type 趋势类别 u:用户总数 i: 用户新增趋势 a: 用户活跃趋势, r:用户付费趋势 j:用户车辆出行趋势(默认:['u','i','a','r','j'] 所有)
* @Request query string type 趋势类别 u:用户总数 i: 用户新增趋势 a: 用户活跃趋势, r:用户付费趋势 j:用户车辆出行趋势(多个',' 隔开 默认:['u','i','a','r','j'])
* @Request query integer n 近N天数据 默认 30天
* @Request query string beginDate 查询开始时间 (2019-12-12)
* @Request query string endDate 查询结束时间 (2019-12-12)
......@@ -285,11 +281,11 @@ class UserController extends Controller {
beginDate = endDate = null;
}else{
beginDate = this.helper.date(-n);
var { yesterday:endDate } = await this._fetch_date_in_cache();
var { yesterday:endDate } = await this._fetch_date_in_cache_();
}
}
type =type?(type.includes(',')?type.split(','):type):['u','i','a','r','j'];
const data = await this._fetch_detail_by_range( { pid, cid, field:type,beginDate, endDate } )
type = type ? ( type.includes(',') ? type.split(',') : type ) : [ 'u', 'i', 'a', 'r', 'j' ];
const data = await this._fetch_detail_by_range_( { pid, cid, field:type,beginDate, endDate } )
this.ctx.body = this.ServerResponse.Success(data);
}
......
......@@ -31,53 +31,43 @@ class UpdateCache extends Subscription {
_group(cities, f) {
const data = {
date:'2000-01-01',
};
function __push(target,obj){
target =target || {}
if(obj){
const {r,u,a,i,j,m,o} = obj;
target['r'] += +r;//续费 renew
target['u'] += +u;//用户总数 user
target['a'] += +a;// 活跃用户数 active
target['i'] += +i;// 新增用户数 increase
target['j'] += +j;// 出行 journey
target['m'] += +m;// 里程 miles
target['o'] += +o;// online 在线时间
}else{
target['r'] = 0;//续费 renew
target['u'] = 0;//用户总数 user
target['a'] = 0;// 活跃用户数 active
target['i'] = 0;// 新增用户数 increase
target['j'] = 0;// 出行 journey
target['m'] = 0.00;// 里程 miles
target['o'] = 0;// online 在线时间
var date= this.app.config.sys.init_date;
function __init_or_plus__(target, obj) {
target = target || {};
if (obj) {
const { r, u, a, i, j, m, o } = obj;
target["r"] += +r; //续费 renew
target["u"] += +u; //用户总数 user
target["a"] += +a; // 活跃用户数 active
target["i"] += +i; // 新增用户数 increase
target["j"] += +j; // 出行 journey
target["m"] += +m; // 里程 miles
target["o"] += +o; // online 在线时间
} else {
target["r"] = 0; //续费 renew
target["u"] = 0; //用户总数 user
target["a"] = 0; // 活跃用户数 active
target["i"] = 0; // 新增用户数 increase
target["j"] = 0; // 出行 journey
target["m"] = 0.0; // 里程 miles
target["o"] = 0; // online 在线时间
}
return target;
};
cities.forEach(function (city) {
const prov_code = f(city);
let { city_code,total_user:u,renew:r,active:a,increase:i,journey:j,miles:m,online_time:o,day } = city
// day = day.replace_all('-','');
data.date=this.helper.moment(day).isAfter(data.date)?day:data.date
if(!data[day]){
data[day] = {
p:{} //省 province
}
data[day] = __push(data[day])
}
data[day] = __push(data[day],{r,u,a,i,j,m,o})
data[day]['p'][prov_code] = data[day]['p'][prov_code] || {}
if(typeof data[day]['p'][prov_code]['u'] === 'undefined'){
data[day]['p'][prov_code] = __push(data[day]['p'][prov_code])
}
data[day]['p'][prov_code] = __push(data[day]['p'][prov_code],{r,u,a,i,j,m,o})
if(!data[day]['p'][prov_code]['c']){
data[day]['p'][prov_code]['c']={}
}
data[day]['p'][prov_code]['c'][city_code]={ u,r,a,i,j,m,o };
}.bind(this));
return data
}
cities.forEach(
function(city) {
const prov_code = f(city);
let { city_code, total_user: u, renew: r, active: a, increase: i, journey: j, miles: m, online_time: o, day } = city;
date = this.helper.moment(day).isAfter(date) ? day : date;
data[day] = data[day] || Object.assign(__init_or_plus__(null),{'p':{}}) //如果day 节点不存在 则 初始化一个
data[day] = __init_or_plus__(data[day], { r, u, a, i, j, m, o }); // 累加全国总数值
data[day]["p"][prov_code] = data[day]["p"][prov_code] || Object.assign(__init_or_plus__(null),{'c':{}}); //如果day 下的 省份 不存在 则 初始化一个
data[day]["p"][prov_code] = __init_or_plus__(data[day]["p"][prov_code], { r, u, a, i, j, m, o }); //累加 prov_code 省份总数据
data[day]["p"][prov_code]["c"][city_code] = { u, r, a, i, j, m, o };
}.bind(this)
);
return { data, date };
}
// task_total_country_cache(){
......@@ -90,32 +80,45 @@ class UpdateCache extends Subscription {
// subscribe 是真正定时任务执行时被运行的函数
async subscribe() {
this.logger.info( "===============执行日常任务-缓存每日统计数据(总30天) begin==================");
this.logger.info("===============执行日常任务-缓存每日统计数据(总30天) begin==================");
const { moment, constant } = this.helper;
const { DATES, USER_SUMMARY_30_DAY } = constant;
var { cache_update_time, cache_data_last_date } = await this.CacheService.get(DATES);
const { cache_update_time_diff } = this.app.config.sys;
if( moment().diff(moment(cache_update_time)) < cache_update_time_diff ) {
this.logger.info( "=============== 距离上一次更新不到 %s 毫秒.不执行更新操作 ==================",cache_update_time_diff );
return ;
}
const yesterday = this.helper.date(-1);
const today = this.helper.date(0);
const day30before = this.helper.date(-30);
// 查询昨天 所有城市 分别 对应的 用户总数 列表
const cities = await this.UserService.user_summary_city_by_day({beginDate:day30before,endDate:yesterday});
const cities = await this.UserService.user_summary_city_by_day({beginDate: day30before, endDate: yesterday});
if (cities.length) {
const data = this._group(cities, city=>city.prov_code);
const value = JSON.stringify(data);
await this.CacheService.set(
this.helper.constant.USER_SUMMARY_30_DAY,
value,
2 * 24 * 60 * 60 //两天过期
);
this.logger.info("user_summary_%s([%s]):%s",data.date,Object.keys(data).join(','),value);
}else{
var {data, date } = this._group(cities, city => city.prov_code);
if( moment(date).isAfter( cache_data_last_date) ){ //当前数据最新时间 大于 上一次缓存数据的最新时间 才写入缓存
const value = JSON.stringify(data);
await this.CacheService.set(
USER_SUMMARY_30_DAY,
value
);
cache_data_last_date = date; //更新缓存数据最新时间
this.logger.info("user_summary_%s([%s]):%s",data.date,Object.keys(data).join(","),value);
}else{
this.logger.info("cache_date:%s date:%s 不写缓存",cache_data_last_date,date);
}
} else {
this.logger.warn("warnning=============user_summary_30_day===========is empty!");
}
//缓存日期.方便业务使用
await this.CacheService.set(
this.helper.constant.DATES,
DATES,
{
today,
yesterday
},
2 * 24 * 60 * 60 //两天过期
yesterday,
cache_data_last_date,
cache_update_time:moment()
}
);
this.logger.info("===============执行日常任务-缓存每日统计数据(总30天) end==================");
}
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 14:32:51
* @Last Modified by: limin
* @Last Modified time: 2019-12-04 11:12:10
* @Last Modified time: 2019-12-05 17:34:43
*/
"use strict";
......@@ -18,7 +18,7 @@ class CacheService extends Service {
this.helper = ctx.helper;
this.PREFIX = ctx.helper.constant.PREFIX;
}
async set(key, value, ex = 60 * 60) {
async set(key, value, ex = this.app.config.sys.cache_expires_time) {
this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex));
}
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:18:37
* @Last Modified by: limin
* @Last Modified time: 2019-12-04 10:59:19
* @Last Modified time: 2019-12-05 13:42:22
*/
const Service = require("egg").Service;
......@@ -76,8 +76,7 @@ class UserService extends Service {
Object.assign(option, {
attributes: [
col("total_user",'total'),
col("t_city.city_name",'city'),
col("update_time",'date')
col("t_city.city_name",'city')
],
include: { model: MCity, attributes: [] },
raw: true
......@@ -140,8 +139,7 @@ class UserService extends Service {
[fn("SUM", col("w_10_20")),'w_10_20'],
[fn("SUM", col("w_20_30")),'w_20_30'],
[fn("SUM", col("w_30_50")),'w_30_50'],
[fn("SUM", col("w_50_")),'w_50_'],
col("update_time",'date')
[fn("SUM", col("w_50_")),'w_50_']
],
raw: true
});
......@@ -225,8 +223,7 @@ class UserService extends Service {
'gender_range',
[fn("SUM", col("total")), "total"],
[fn("SUM", col("male")), "male"],
[fn("SUM", col("female")), "female"],
col("update_time",'date')
[fn("SUM", col("female")), "female"]
],
group:'gender_range',
raw: true
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-16 09:26:53
* @Last Modified by: limin
* @Last Modified time: 2019-11-26 18:29:28
* @Last Modified time: 2019-12-05 17:52:57
*/
/* eslint valid-jsdoc: "off" */
......@@ -127,5 +127,14 @@ module.exports = app => {
routerMap: true,
enable: true
};
config.sys={
// 缓存更新时间间隔 (毫秒)
cache_update_time_diff : 1*60*1000,
// 数据缓存过期时间 (秒)
cache_expires_time: 2 * 24 * 60 * 60,
// 初始化 日期
init_date:'2000-01-01'
}
return config;
};
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!