Commit bd2cd596 by liimin

新增实时播报激活数据接口

1 parent cc175c07
const path = require('path'); const path = require('path');
const Queue = require("./app/common/queue");
// module.exports = app => { // module.exports = app => {
// app.beforeStart(async function() { // app.beforeStart(async function() {
// // 应用会等待这个函数执行完成才启动 // // 应用会等待这个函数执行完成才启动
...@@ -24,26 +25,63 @@ const path = require('path'); ...@@ -24,26 +25,63 @@ const path = require('path');
`) `)
} }
async didReady() { async didReady() {
// 应用已经启动完毕
// 加载所有的校验规则 const ctx = await this.app.createAnonymousContext();
console.log('================加载校验规则================')
console.log('\r\n 应用启动成功!\r\n')
console.log(' ◆ 1.加载校验规则\r\n')
await this._init_user_validations_(ctx);
console.log(' ◆ 2.重置时间对象\r\n')
await this._init_user_date_times_(ctx)
console.log(' ◆ 3.初始化激活消息队列\r\n')
await this._init_user_activation_queue_(ctx)
}
async _init_user_validations_() {
const directory = path.join(this.app.config.baseDir, './app/validate'); const directory = path.join(this.app.config.baseDir, './app/validate');
this.app.loader.loadToApp(directory, 'validate'); this.app.loader.loadToApp(directory, 'validate');
}
console.log('================重置时间对象================') async _init_user_date_times_(ctx) {
const ctx = await this.app.createAnonymousContext();
const { service, helper } = ctx; const { service, helper } = ctx;
const { date, constant, moment } = helper const { date, constant, moment } = helper
const yesterday = date(-1); const yesterday = date(-1);
const today = date(0); const today = date(0);
var { init_date, cache_update_time_diff } = this.app.config.sys; var { init_date, user_cache_update_time_diff } = this.app.config.sys;
await service.cache.set(constant.DATES,{ await service.cache.set(constant.DATES,{
today, today,
yesterday, yesterday,
cache_data_last_date:init_date, cache_data_last_date:init_date,
cache_update_time:moment().subtract(cache_update_time_diff +1 ,'milliseconds'), cache_update_time:moment().subtract(user_cache_update_time_diff +1 ,'milliseconds'),
}); });
} }
async _init_user_activation_queue_(ctx) {
let queue = new Queue({size:this.app.config.sys.user_activation_queue_size});
queue.enqueue(...[
{ id: 0, name: "张三", pid: 33 },
{ id: 1, name: "李四", pid: 34 },
{ id: 2, name: "王五", pid: 11 },
{ id: 3, name: "赵六", pid: 15 },
{ id: 4, name: "张三", pid: 33 },
{ id: 5, name: "李四", pid: 34 },
{ id: 6, name: "王五", pid: 11 },
{ id: 7, name: "赵六", pid: 15 },
{ id: 8, name: "赵六", pid: 15 },
{ id: 9, name: "赵六", pid: 15 }
]);
this.app.queue = queue;
//调用一次真实数据 覆盖初始化数据
const { service, helper } = ctx;
const { USER_ACTIVE_DATA_LASI_ID } = helper.constant;
const _last_id = await service.cache.get(USER_ACTIVE_DATA_LASI_ID);
const data = this.app.queue.peek();
this.app.queue.fill(async ()=>await service.screen.user.activation({ limit: queue.size(), last_id:_last_id }),data)
.then(last_id=>last_id && service.cache.set(USER_ACTIVE_DATA_LASI_ID,last_id))
}
} }
module.exports = AppBootHook; module.exports = AppBootHook;
...@@ -2,11 +2,12 @@ ...@@ -2,11 +2,12 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:20:15 * @Date: 2019-11-21 11:20:15
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-02 12:16:54 * @Last Modified time: 2019-12-07 14:14:31
*/ */
module.exports = { module.exports = {
PREFIX: '_glsx_data_screen_', PREFIX: '_glsx_data_screen_',
USER_SUMMARY_30_DAY:'user_summary_30_day', USER_SUMMARY_30_DAY:'user_summary_30_day',
DATES:'dates' DATES:'dates',
USER_ACTIVE_DATA_LASI_ID:'user_active_data_last_id'
}; };
\ No newline at end of file \ No newline at end of file
/* /*
* @Author: limin * @Author: limin
* @Date: 2019-12-06 14:58:35 * @Date: 2019-12-06 14:58:35
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-06 18:22:13 * @Last Modified time: 2019-12-07 16:11:22
*/ */
const items = new WeakMap(); //WeakMap对象是密钥/值对的集合,其中密钥被弱引用。键必须是对象,值可以是任意值。 // const items = new WeakMap(); //WeakMap对象是密钥/值对的集合,其中密钥被弱引用。键必须是对象,值可以是任意值。
module.exports = class Queue { // module.exports = class Queue {
constructor() { // constructor() {
items.set(this, []); // items.set(this, []);
} // }
enqueue(...element) { // enqueue(...element) {
//向队列尾部添加一个(或多个)新的项 // //向队列尾部添加一个(或多个)新的项
let q = items.get(this); // let q = items.get(this);
q.push(...element); // q.push(...element);
} // }
dequeue() { // dequeue() {
//移除队列的第一个(排在队列最前面的)项,并返回被移除的元素。 // //移除队列的第一个(排在队列最前面的)项,并返回被移除的元素。
let q = items.get(this); // let q = items.get(this);
let r = q.shift(); // let r = q.shift();
return r; // return r;
} // }
front() { // front() {
//返回队列中第一个元素——最先被添加,也将是最先被移除的元素。队列不做任何变动(不移除元素,只返回元素信息) // //返回队列中第一个元素——最先被添加,也将是最先被移除的元素。队列不做任何变动(不移除元素,只返回元素信息)
let q = items.get(this); // let q = items.get(this);
return q[0]; // return q[0];
} // }
// isEmpty() {
// //如果队列中不包含任何元素,返回true,否则返回false。
// return items.get(this).length == 0;
// }
// size() {
// //返回队列包含的元素个数,与数组的length属性类似。
// let q = items.get(this);
// return q.length;
// }
// clear() {
// //清空队列里面的元素。
// items.set(this, []);
// }
// print() {
// //打印队列为String到控制台
// console.log(this.toString());
// }
// toString() {
// //输出队列以String模式。
// return items.get(this).toString();
// }
// }
module.exports = class Queue {
constructor({size}) {
this._elements = [];
this._size = size;
}
isArray(arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}
isEmpty() { isEmpty() {
//如果队列中不包含任何元素,返回true,否则返回false。 return this._elements.length === 0;
return items.get(this).length == 0; }
q() {
return this._elements;
} }
size() { size() {
//返回队列包含的元素个数,与数组的length属性类似。 return this._size;
let q = items.get(this);
return q.length;
} }
enqueue(...element) {
clear() { if (this.isArray(...element)) {
//清空队列里面的元素。 this._elements = this._elements.concat(...element);
items.set(this, []); return;
}
this._elements.push(...element);
} }
/**
print() { * 出列 前 N个对象 并返回 出列的对象
//打印队列为String到控制台 * @param {*} n 出列 前N 个
console.log(this.toString()); */
dequeue(n) {
if (this.isEmpty()) throw new Error("Queue is empty");
if (n) {
var r = [];
this._elements = this._elements.filter((item, index) => {
index < n && r.push(item);
return index >= n;
});
return r;
}
return this._elements.shift();
} }
peek() {
toString() { const r = this._elements;
//输出队列以String模式。 this._elements = [];
return items.get(this).toString(); return r;
}
async fill(fn,last_peek_data) {
const result = await fn();
const _result_size = result.length;
if (!_result_size) {
this.enqueue(last_peek_data);
} else if (_result_size < this._size) {
// 从上一次返回的数据中 获取相差的几条数据 补充到最新数据的末尾 保证队列数据的数量 公式为: [data][_result_size]
const _last_data_list = data.filter((item, index) => index >= _result_size);
this.enqueue(...result, ..._last_data_list);
} else {
this.enqueue(result);
}
return _result_size? result.reduce((pre, next) => Math.max(pre, next.id), 0): 0;
}
first() {
if (this.isEmpty()) throw new Error("Queue is empty");
return this._elements[0];
} }
} };
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:20:01 * @Date: 2019-11-21 11:20:01
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-06 18:22:23 * @Last Modified time: 2019-12-07 16:01:48
*/ */
"use strict"; "use strict";
...@@ -23,6 +23,7 @@ class UserController extends Controller { ...@@ -23,6 +23,7 @@ class UserController extends Controller {
this.CacheService = ctx.service.cache; //redis 缓存服务 this.CacheService = ctx.service.cache; //redis 缓存服务
this.ServerResponseCode = ctx.response.ServerResponseCode; this.ServerResponseCode = ctx.response.ServerResponseCode;
this.ServerResponse = ctx.response.ServerResponse; this.ServerResponse = ctx.response.ServerResponse;
this.queue = ctx.app.queue;
} }
/** /**
...@@ -180,10 +181,6 @@ class UserController extends Controller { ...@@ -180,10 +181,6 @@ class UserController extends Controller {
* @Request query integer pid 省份id * @Request query integer pid 省份id
*/ */
async total({ query: { pid,cid } }) { async total({ query: { pid,cid } }) {
// const queue = new this.helper.Queue()
// queue.enqueue(1,2,3,4,5);
// console.log(queue.dequeue(5));
// console.log(queue.size());
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 = await this.UserService.user_realtime({ pid, cid });
const realtime_total = realtime.reduce((pre,next)=>pre + +next['increase'],0); const realtime_total = realtime.reduce((pre,next)=>pre + +next['increase'],0);
...@@ -283,7 +280,19 @@ class UserController extends Controller { ...@@ -283,7 +280,19 @@ class UserController extends Controller {
const data = await this._fetch_detail_by_range_( { pid, cid, field:type,beginDate, endDate } ) const data = await this._fetch_detail_by_range_( { pid, cid, field:type,beginDate, endDate } )
this.ctx.body = this.ServerResponse.Success(data); this.ctx.body = this.ServerResponse.Success(data);
} }
/**
* @Router GET /screen/user/activation
* @Description 实时激活数据播报
* @Request query integer pid 省份id
*/
async activation({ query: { pid } }) {
const data = this.queue.peek();
const { USER_ACTIVE_DATA_LASI_ID } = this.helper.constant;
const _last_id = await this.CacheService.get(USER_ACTIVE_DATA_LASI_ID);
this.queue.fill(async ()=>await this.UserService.activation({ pid, limit: this.queue.size(), last_id:_last_id }),data)
.then(last_id=>last_id && this.CacheService.set(USER_ACTIVE_DATA_LASI_ID,last_id))
this.ctx.body = this.ServerResponse.Success(data);
}
} }
module.exports = UserController; module.exports = UserController;
...@@ -2,15 +2,13 @@ ...@@ -2,15 +2,13 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:19:43 * @Date: 2019-11-21 11:19:43
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-06 15:10:08 * @Last Modified time: 2019-12-07 13:35:15
*/ */
const moment = require("moment"); const moment = require("moment");
const constant = require("../common/constant"); const constant = require("../common/constant");
const queue = require("../common/queue");
exports.moment = moment; exports.moment = moment;
exports.Queue = queue;
/* /*
* string.replace_all()---字符替换所有指定字符 * string.replace_all()---字符替换所有指定字符
* @parameter: from--原文本要替换值 * @parameter: from--原文本要替换值
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:18:45 * @Date: 2019-11-21 11:18:45
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-04 14:50:35 * @Last Modified time: 2019-12-07 11:48:43
*/ */
module.exports = app => { module.exports = app => {
...@@ -13,4 +13,5 @@ module.exports = app => { ...@@ -13,4 +13,5 @@ module.exports = app => {
app.router.get('/screen/user/car_brand_range', app.controller.screen.user.car_brand_range); app.router.get('/screen/user/car_brand_range', app.controller.screen.user.car_brand_range);
app.router.get('/screen/user/drive_range', app.controller.screen.user.drive_range); app.router.get('/screen/user/drive_range', app.controller.screen.user.drive_range);
app.router.get('/screen/user/trend', app.controller.screen.user.trend); app.router.get('/screen/user/trend', app.controller.screen.user.trend);
app.router.get('/screen/user/activation', app.controller.screen.user.activation);
}; };
\ No newline at end of file \ No newline at end of file
...@@ -84,9 +84,9 @@ class UpdateCache extends Subscription { ...@@ -84,9 +84,9 @@ class UpdateCache extends Subscription {
const { moment, constant } = this.helper; const { moment, constant } = this.helper;
const { DATES, USER_SUMMARY_30_DAY } = constant; const { DATES, USER_SUMMARY_30_DAY } = constant;
var { cache_update_time, cache_data_last_date } = await this.CacheService.get(DATES); var { cache_update_time, cache_data_last_date } = await this.CacheService.get(DATES);
const { cache_update_time_diff } = this.app.config.sys; const { user_cache_update_time_diff } = this.app.config.sys;
if( moment().diff(moment(cache_update_time)) < cache_update_time_diff ) { if( moment().diff(moment(cache_update_time)) < user_cache_update_time_diff ) {
this.logger.info( "=============== 距离上一次更新不到 %s 毫秒.不执行更新操作 ==================",cache_update_time_diff ); this.logger.info( "=============== 距离上一次更新不到 %s 毫秒.不执行更新操作 ==================",user_cache_update_time_diff );
return ; return ;
} }
const yesterday = this.helper.date(-1); const yesterday = this.helper.date(-1);
......
...@@ -18,7 +18,7 @@ class CacheService extends Service { ...@@ -18,7 +18,7 @@ class CacheService extends Service {
this.helper = ctx.helper; this.helper = ctx.helper;
this.PREFIX = ctx.helper.constant.PREFIX; this.PREFIX = ctx.helper.constant.PREFIX;
} }
async set(key, value, ex = this.app.config.sys.cache_expires_time) { async set(key, value, ex = this.app.config.sys.user_cache_expires_time) {
this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex)); this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex));
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:18:37 * @Date: 2019-11-21 11:18:37
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-05 13:42:22 * @Last Modified time: 2019-12-07 15:04:32
*/ */
const Service = require("egg").Service; const Service = require("egg").Service;
...@@ -231,6 +231,28 @@ class UserService extends Service { ...@@ -231,6 +231,28 @@ class UserService extends Service {
const data = await MUserGender.findAll(option); const data = await MUserGender.findAll(option);
return data; return data;
} }
/**
* @param field {String}
* @param value {String}
* @return {Promise.<boolean>}
* @Description 获取用户性别年龄数量占比
*/
async activation({ pid, limit, last_id }) {
const { app, helper, MUserGender } = this;
const { Op } = app.Sequelize
var option = helper.seq_option({ pid, limit });
Object.assign(option.where,{
id:{
[Op.gt]: last_id,
}
})
Object.assign(option, {
raw: true
});
const data = await MUserGender.findAll(option);
return data;
}
} }
module.exports = UserService; module.exports = UserService;
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-16 09:26:53 * @Date: 2019-11-16 09:26:53
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-12-05 17:52:57 * @Last Modified time: 2019-12-07 12:19:13
*/ */
/* eslint valid-jsdoc: "off" */ /* eslint valid-jsdoc: "off" */
...@@ -129,12 +129,14 @@ module.exports = app => { ...@@ -129,12 +129,14 @@ module.exports = app => {
}; };
config.sys={ config.sys={
// 缓存更新时间间隔 (毫秒)
cache_update_time_diff : 1*60*1000,
// 数据缓存过期时间 (秒)
cache_expires_time: 2 * 24 * 60 * 60,
// 初始化 日期 // 初始化 日期
init_date:'2000-01-01' init_date:'2000-01-01',
// 数据缓存过期时间 (秒)
user_cache_expires_time: 2 * 24 * 60 * 60,
// 缓存更新时间间隔 (毫秒)
user_cache_update_time_diff : 1 * 60 * 1000,
// 激活用户队列大小
user_activation_queue_size : 10
} }
return config; return config;
}; };
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!