node

node

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
javascript/jQuery

javascript/jQuery

一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。
MongoDB

MongoDB

MongoDB 是一个基于分布式文件存储的数据库
openstack

openstack

OpenStack是一个由NASA(美国国家航空航天局)和Rackspace合作研发并发起的,以Apache许可证授权的自由软件和开放源代码项目。
VUE

VUE

一套构建用户界面的渐进式框架。与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计。
bootstrap

bootstrap

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.
HTML

HTML

超文本标记语言,标准通用标记语言下的一个应用。
CSS/SASS/SCSS/Less

CSS/SASS/SCSS/Less

层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。
PHP

PHP

PHP(外文名:PHP: Hypertext Preprocessor,中文名:“超文本预处理器”)是一种通用开源脚本语言。语法吸收了C语言、Java和Perl的特点,利于学习,使用广泛,主要适用于Web开发领域。PHP 独特的语法混合了C、Java、Perl以及PHP自创的语法。它可以比CGI或者Perl更快速地执行动态网页。用PHP做出的动态页面与其他的编程语言相比,PHP是将程序嵌入到HTML(标准通用标记语言下的一个应用)文档中去执行,执行效率比完全生成HTML标记的CGI要高许多;PHP还可以执
每天进步一点点

每天进步一点点

乌法把门的各累笑寂静
求职招聘

求职招聘

猎头招聘专用栏目
Python

Python

一种解释型、面向对象、动态数据类型的高级程序设计语言。

OpenResty安装

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 552 次浏览 • 2023-02-06 13:55 • 来自相关话题

1、获取预编译包
wget https://openresty.org/package/ ... .repo 2、移动编译包到etc目录
sudo mv openresty.repo /etc/yum.repos.d/ 如果需要更新资源包执行如下命令进行更新
sudo yum check-update3、安装软件包,默认安装在/usr/local/openresty目录下
sudo yum install -y openresty4、 启动nginx
#启动
/usr/local/openresty/nginx/sbin/nginx
#重启
/usr/local/openresty/nginx/sbin/nginx -s reload
#停止
/usr/local/openresty/nginx/sbin/nginx -s stop 查看全部
1、获取预编译包
wget https://openresty.org/package/ ... .repo
 2、移动编译包到etc目录
sudo mv openresty.repo /etc/yum.repos.d/
 如果需要更新资源包执行如下命令进行更新
sudo yum check-update
3、安装软件包,默认安装在/usr/local/openresty目录下
sudo yum install -y openresty
4、 启动nginx
#启动
/usr/local/openresty/nginx/sbin/nginx
#重启
/usr/local/openresty/nginx/sbin/nginx -s reload
#停止
/usr/local/openresty/nginx/sbin/nginx -s stop

RabbitMQ amqplib 死信和延时队列操作

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 743 次浏览 • 2022-06-02 01:00 • 来自相关话题

conn.js

const amqp = require('amqplib');
let connection = null;
module.exports = {
    connection,
    init: () => amqp.connect({
        protocol: 'amqp',
        hostname: '127.0.0.1',
        port: 5672,
        username: 'admin',
        password: '*********',
        frameMax: 0,
        heartbeat: 30,
        vhost: '/',
        client_provided_name: 'BFF'
    }).then(conn => {
        connection = conn;
        console.log('rabbitmq connect success');
        return connection;
    })
}
 
死信
 
pub

const rabbitmq = require('./conn/mqtt');
async function producerDLX(connnection) {
    const testExchange = 'testEx';
    const testQueue = 'testQu';
    const testExchangeDLX = 'testExDLX';
    const testRoutingKeyDLX = 'testRoutingKeyDLX';
    const ch = await connnection.createChannel();
    await ch.assertExchange(testExchange, 'direct', {
        durable: true
    });
    const {queue} = await ch.assertQueue(testQueue, {
        deadLetterExchange: testExchangeDLX,
        deadLetterRoutingKey: testRoutingKeyDLX,
    });
    await ch.bindQueue(queue, testExchange);
    const msg = {
        'ut':new Date() -0
    };
    // console.log(msg)
    await ch.sendToQueue(queue, Buffer.from(JSON.stringify(msg)), {
        expiration: 10000
    });
    ch.close();
}
rabbitmq.init().then(conn => {
        producerDLX(conn)
})
 
sub

const rabbitmq = require('./conn/mqtt');
async function consumerDLX(connnection) {
    const testExchangeDLX = 'testExDLX';
    const testRoutingKeyDLX = 'testRoutingKeyDLX';
    const testQueueDLX = 'testQueueDLX';
    const ch = await connnection.createChannel();
    await ch.assertExchange(testExchangeDLX, 'direct', {
        durable: true
    });
    const {
        queue
    } = await ch.assertQueue(testQueueDLX, {
        exclusive: false,
    });
    await ch.bindQueue(queue, testExchangeDLX, testRoutingKeyDLX);
    await ch.consume(queue, msg => {
        const CONTENT = msg.content.toString();
        console.log(new Date() - 0- JSON.parse(CONTENT).ut)
        // console.log('consumer msg:');
    }, {
        noAck: true
    });
}
rabbitmq.init().then(connection => consumerDLX(connection));
 
延时队列
需要在rabbitmq中安装对应的延时插件
pub

const rabbitmq = require('./conn/mqtt');
async function producerDLX(connnection) {
    const EXCHANGE = 'zdnf-xdm'
    const ch = await connnection.createChannel();
    await ch.assertExchange(EXCHANGE, 'x-delayed-message', {
        durable: true,
        'x-delayed-type': 'topic'
    });
    const {
        queue
    } = await ch.assertQueue('xdpub-test');
    await ch.bindQueue(queue, EXCHANGE);
    const msg = {
        'ut': new Date() - 0
    };
    // console.log(msg)
    await ch.publish(EXCHANGE,'rtk-xdpub-test', Buffer.from(JSON.stringify(msg)), {
        headers: {
            'x-delay': 10000, // 一定要设置,否则无效
        }
    });
    ch.close();
}
rabbitmq.init().then(conn => {
    // setInterval(() => {
        producerDLX(conn)
    // }, 3000);
})
 
 
sub
 

const rabbitmq = require('./conn/mqtt');
async function consumerDLX(connnection) {
    const EXCHANGE = 'zdnf-xdm'
    const ch = await connnection.createChannel();
    await ch.assertExchange(EXCHANGE, 'x-delayed-message', {
        durable: true,
        'x-delayed-type': 'topic'
    });
    ch.prefetch(1);
    const {
        queue
    } = await ch.assertQueue('xdpub-test');
     await ch.bindQueue(queue, EXCHANGE, 'rtk-xdpub-test');
    await ch.consume(queue, msg => {
        const CONTENT = msg.content.toString();
        console.log(new Date() - 0 - JSON.parse(CONTENT).ut)
        // console.log('consumer msg:');
    }, {
        noAck: true
    });
}
rabbitmq.init().then(connection => consumerDLX(connection));
  查看全部
conn.js

const amqp = require('amqplib');
let connection = null;
module.exports = {
    connection,
    init: () => amqp.connect({
        protocol: 'amqp',
        hostname: '127.0.0.1',
        port: 5672,
        username: 'admin',
        password: '*********',
        frameMax: 0,
        heartbeat: 30,
        vhost: '/',
        client_provided_name: 'BFF'
    }).then(conn => {
        connection = conn;
        console.log('rabbitmq connect success');
        return connection;
    })
}
 
死信
 
pub

const rabbitmq = require('./conn/mqtt');
async function producerDLX(connnection) {
    const testExchange = 'testEx';
    const testQueue = 'testQu';
    const testExchangeDLX = 'testExDLX';
    const testRoutingKeyDLX = 'testRoutingKeyDLX';
    const ch = await connnection.createChannel();
    await ch.assertExchange(testExchange, 'direct', {
        durable: true
    });
    const {queue} = await ch.assertQueue(testQueue, {
        deadLetterExchange: testExchangeDLX,
        deadLetterRoutingKey: testRoutingKeyDLX,
    });
    await ch.bindQueue(queue, testExchange);
    const msg = {
        'ut':new Date() -0
    };
    // console.log(msg)
    await ch.sendToQueue(queue, Buffer.from(JSON.stringify(msg)), {
        expiration: 10000
    });
    ch.close();
}
rabbitmq.init().then(conn => {
        producerDLX(conn)
})
 
sub

const rabbitmq = require('./conn/mqtt');
async function consumerDLX(connnection) {
    const testExchangeDLX = 'testExDLX';
    const testRoutingKeyDLX = 'testRoutingKeyDLX';
    const testQueueDLX = 'testQueueDLX';
    const ch = await connnection.createChannel();
    await ch.assertExchange(testExchangeDLX, 'direct', {
        durable: true
    });
    const {
        queue
    } = await ch.assertQueue(testQueueDLX, {
        exclusive: false,
    });
    await ch.bindQueue(queue, testExchangeDLX, testRoutingKeyDLX);
    await ch.consume(queue, msg => {
        const CONTENT = msg.content.toString();
        console.log(new Date() - 0- JSON.parse(CONTENT).ut)
        // console.log('consumer msg:');
    }, {
        noAck: true
    });
}
rabbitmq.init().then(connection => consumerDLX(connection));
 
延时队列

需要在rabbitmq中安装对应的延时插件


pub

const rabbitmq = require('./conn/mqtt');
async function producerDLX(connnection) {
    const EXCHANGE = 'zdnf-xdm'
    const ch = await connnection.createChannel();
    await ch.assertExchange(EXCHANGE, 'x-delayed-message', {
        durable: true,
        'x-delayed-type': 'topic'
    });
    const {
        queue
    } = await ch.assertQueue('xdpub-test');
    await ch.bindQueue(queue, EXCHANGE);
    const msg = {
        'ut': new Date() - 0
    };
    // console.log(msg)
    await ch.publish(EXCHANGE,'rtk-xdpub-test', Buffer.from(JSON.stringify(msg)), {
        headers: {
            'x-delay': 10000, // 一定要设置,否则无效
        }
    });
    ch.close();
}
rabbitmq.init().then(conn => {
    // setInterval(() => {
        producerDLX(conn)
    // }, 3000);
})
 
 
sub
 

const rabbitmq = require('./conn/mqtt');
async function consumerDLX(connnection) {
    const EXCHANGE = 'zdnf-xdm'
    const ch = await connnection.createChannel();
    await ch.assertExchange(EXCHANGE, 'x-delayed-message', {
        durable: true,
        'x-delayed-type': 'topic'
    });
    ch.prefetch(1);
    const {
        queue
    } = await ch.assertQueue('xdpub-test');
     await ch.bindQueue(queue, EXCHANGE, 'rtk-xdpub-test');
    await ch.consume(queue, msg => {
        const CONTENT = msg.content.toString();
        console.log(new Date() - 0 - JSON.parse(CONTENT).ut)
        // console.log('consumer msg:');
    }, {
        noAck: true
    });
}
rabbitmq.init().then(connection => consumerDLX(connection));
 

eggjs egg-ioredis 中使用lua 脚本 (redis lua 脚本的扫盲帖 )

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 1033 次浏览 • 2022-03-28 23:47 • 来自相关话题

基础语法解析调用Lua脚本的语法:
$ redis-cli --eval path/to/redis.lua numberkeys KEYS[1] KEYS[2] , ARGV[1] ARGV[2] ...

--eval,告诉redis-cli读取并运行后面的lua脚本
path/to/redis.lua,是lua脚本的位置,也可以直接为脚本字符串。是一个Lua 5.1 script。
numberkeys ,指定后续参数有几个key。
KEYS[1] KEYS[2],是要操作的键,可以指定多个,在lua脚本中通过KEYS[1], KEYS[2]获取
ARGV[1] ARGV[2],参数,在lua脚本中通过ARGV[1], ARGV[2]获取。实例脚本 批量查询hash的值 hget 和切换db 以eggjs为例/**
* @summary 竞拍列表
* @description 1.type 【1】检测用户是否已报名 【2】用户报名的拍卖列表
* @router GET /api/v1/user/auction/auction/list
* @request query string page 第几页
* @request query string limit 每页几个
* @request query string type 类型
* @request query string status 状态
* @apikey Authorization
* @response 200 ACRES
*/
async index() {
const {
ctx,
ctx:{
uid,
query:{
page=1,
limit=12,
type,
status
}
}
}= this;
const RDS = await ctx.app.redis.get('auctionRoom')
try {
// 查询符合条件的hash key
const [[],LIST] = await RDS.sscan(`ar:u:${uid}`,(page-1)*limit,'count',limit);

// 注册脚本
// 1 声明输出的类型 rst {} {}对应key 为数组的下标记
// 2 格式化输入的参数KEYS 对应lua的numberkeys 为1
// 3 lua中切换db 也可以做多个参数 如KEYS2 这里我是固定的 所以只传一个 KEYS
// 4,5,6 执行redis的hget脚本 .. v 为lua中的链接符号
// 7 返回值
await RDS.defineCommand("hmgetall", {
lua: `local rst={};
local id=cjson.decode(KEYS[1]);
redis.call('select',13);
for i,v in pairs(id)
do rst[i]=redis.call('hget', 'ar:' .. v,'meta_info')
end;
return rst;`,
})
// 使用脚本并格式化 输出
ctx.body = (await RDS.hmgetall(1,JSON.stringify(LIST.map(e=>`${e}`)))).reduce((a,b)=>{
a['list'].push(JSON.parse(b));
return a
},{list:,page:{limit,page}})
} catch (err) {
console.log(err)
return ctx.body = {
code: 211,
message: ctx.app.config.env === 'local' ? `${(err.message)}`:'服务器忙,请稍后重试!',
data: err.errors
}
}
}[/i]
 
  查看全部
基础语法解析
调用Lua脚本的语法:
$ redis-cli --eval path/to/redis.lua numberkeys KEYS[1] KEYS[2] , ARGV[1] ARGV[2] ...

--eval,告诉redis-cli读取并运行后面的lua脚本
path/to/redis.lua,是lua脚本的位置,也可以直接为脚本字符串。是一个Lua 5.1 script。
numberkeys ,指定后续参数有几个key。
KEYS[1] KEYS[2],是要操作的键,可以指定多个,在lua脚本中通过KEYS[1], KEYS[2]获取
ARGV[1] ARGV[2],参数,在lua脚本中通过ARGV[1], ARGV[2]获取。
实例脚本 批量查询hash的值 hget 和切换db 以eggjs为例
/**
* @summary 竞拍列表
* @description 1.type 【1】检测用户是否已报名 【2】用户报名的拍卖列表
* @router GET /api/v1/user/auction/auction/list
* @request query string page 第几页
* @request query string limit 每页几个
* @request query string type 类型
* @request query string status 状态
* @apikey Authorization
* @response 200 ACRES
*/
async index() {
const {
ctx,
ctx:{
uid,
query:{
page=1,
limit=12,
type,
status
}
}
}= this;
const RDS = await ctx.app.redis.get('auctionRoom')
try {
// 查询符合条件的hash key
const [[],LIST] = await RDS.sscan(`ar:u:${uid}`,(page-1)*limit,'count',limit);

// 注册脚本
// 1 声明输出的类型 rst {} {}对应key 为数组的下标记
// 2 格式化输入的参数KEYS 对应lua的numberkeys 为1
// 3 lua中切换db 也可以做多个参数 如KEYS2 这里我是固定的 所以只传一个 KEYS
// 4,5,6 执行redis的hget脚本 .. v 为lua中的链接符号
// 7 返回值
await RDS.defineCommand("hmgetall", {
lua: `local rst={};
local id=cjson.decode(KEYS[1]);
redis.call('select',13);
for i,v in pairs(id)
do rst[i]=redis.call('hget', 'ar:' .. v,'meta_info')
end;
return rst;`,
})
// 使用脚本并格式化 输出
ctx.body = (await RDS.hmgetall(1,JSON.stringify(LIST.map(e=>`${e}`)))).reduce((a,b)=>{
a['list'].push(JSON.parse(b));
return a
},{list:,page:{limit,page}})
} catch (err) {
console.log(err)
return ctx.body = {
code: 211,
message: ctx.app.config.env === 'local' ? `${(err.message)}`:'服务器忙,请稍后重试!',
data: err.errors
}
}
}[/i]

 
 

保留2位

javascript/jQuerylopo1983 发表了文章 • 0 个评论 • 941 次浏览 • 2021-09-29 20:51 • 来自相关话题

retain(key, pow = 2) {
            const [k1, k2] = key.split('.')
            if(!k1 || !k2) return
            if(this[k1][k2]==0) return this.$set(this[k1], k2, '')
            const multiple =  Math.pow(10, Number(pow))
            const num = ~~(Number(this[k1][k2]) * multiple) / multiple
            this.$set(this[k1], k2, num)
        } 查看全部
retain(key, pow = 2) {
            const [k1, k2] = key.split('.')
            if(!k1 || !k2) return
            if(this[k1][k2]==0) return this.$set(this[k1], k2, '')
            const multiple =  Math.pow(10, Number(pow))
            const num = ~~(Number(this[k1][k2]) * multiple) / multiple
            this.$set(this[k1], k2, num)
        }

centos nginx 启动

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 865 次浏览 • 2021-07-30 15:56 • 来自相关话题

nginx -c /etc/nginx/nginx.conf
 

nginx -c /etc/nginx/nginx.conf
 

mongodb 用户地址模型

mongodblopo1983 发表了文章 • 0 个评论 • 1399 次浏览 • 2020-09-28 14:20 • 来自相关话题

module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const { logger, helper } = app.createAnonymousContext();
const {
objToQuery
} = helper;
const conn = app.mongooseDB.get('mp');
const AccountUserAddressSchema = new Schema({
// 默认地址
default_id: {
type: Schema.Types.ObjectId,
default: null
},
// 用户id
_uid: {
type: Schema.Types.ObjectId
},
// 标签
tags: {
type: Array,
default: ['家', '公司', '学校']
},
// 地址列表
address: [{
// 收货人姓名
userName: {
type: String,
required: true
},
// 邮编
postalCode: {
type: String
},
// 省市
provinceName: {
type: String,
required: true
},
// 市
cityName: {
type: String,
required: true
},
// 区/县
countyName: {
type: String,
required: true
},
// 详细地址
detailInfo: {
type: String,
required: true
},
// 联系电话
telNumber: {
type: String,
required: true
},
// 状态 [[0,'删除'],[1,'正常']]
status: {
type: Number,
default: 1
},
// 标签
tag: String,
// 添加时间
addTime: {
type: Date,
default: new Date()
},
deleteTime: Date
}]
});
AccountUserAddressSchema.statics = {
// 添加
addOne: async function(_uid, BODYS) {
const { is_default } = BODYS;
const MODEL = this.findOneAndUpdate({
_uid
}, {
$push: {
'address': {...BODYS }
},
// ...isDefault && { default_id: _id }
}, {
new: true,
fields: 'cars default_id -_id'
});
try {
const RBD = await MODEL;
return !!RBD
} catch (error) {
console.log(error)
}
},
// 更新地址
updateOne: async function(_uid, _id, BODYS) {
// const { isDefault } = BODYS;
// delete BODYS.isDefault;
const MODEL = this.findOneAndUpdate({
_uid,
'address._id': _id
}, {
$set: {...objToQuery(BODYS, 'address') }
}, {
fields: 'address default_id -_id'
});
try {
// 修改数据
const DATAS = await MODEL;
// 修改默认
// !!isDefault && await this.setDefault(_uid, isDefault, _id);
return !!DATAS.address.length ? BODYS : { code: 211, message: '更新失败' }
} catch (error) {
return error
}
},
// 列表
list: async function(_uid) {
const MODEL = this.aggregate([{
$match: {
_uid: mongoose.Types.ObjectId(_uid)
}
}, {
$unwind: '$address'
}, {
$match: {
'address.deleteTime': { $exists: false }
}
}, {
$addFields: {
'address.isDefault': {
$eq: ['$default_id', '$address._id']
}
}
}, {
$replaceRoot: { newRoot: "$address" }
}]);
// const MODEL = this.find({ _uid })
try {
const RBD = await MODEL;
return RBD.length ? RBD : await this.initAddress(_uid)
} catch (error) {
console.log(error)
}
},
// 删除一个
delOne: async function(_uid, _id) {
const MODEL = this.findOneAndUpdate({
_uid,
'address._id': _id
}, {
'address.$.status': 0,
'address.$.deleteTime': new Date(),
});
try {
const RBD = await MODEL;
return { _id }
} catch (error) {

}
},
// 初始化用地址
initAddress: async function(_uid) {
const MODEL = this.create({ _uid: mongoose.Types.ObjectId(_uid) });
try {
const DATAS = await MODEL;
return DATAS
} catch (error) {
console.log(error)
}
},
// 获取单一数据
getOne: async function(_uid, _id) {
const MODEL = this.aggregate([{
$match: { _uid: mongoose.Types.ObjectId(_uid) }
}, {
$unwind: '$address'
}, {
$project: {
address: 1,
_id: 1,
default_id: 1,
}
}, {
$addFields: {
'address.isDefault': {
$eq: [{ $toString: '$default_id' }, _id]
}
}
}, {
$match: {
'address.deleteTime': { $exists: false },
'address._id': mongoose.Types.ObjectId(_id),
}
}, {
$replaceRoot: { newRoot: "$address" }
}]);
try {
if (_id !== "default") {
const DATAS = await MODEL;
return DATAS.length ? DATAS[0] : {}
}
} catch (error) {
console.log(error)
return error
}
},
// 获取默认地址
getDefault: async function(_uid) {
const MODEL = this.findOne({ _uid }, {}, {
fields: 'default_id -_id'
});
try {
const { default_id } = await MODEL;
return await this.getOne(_uid, default_id)
} catch (error) {
console.log(error);
return error
}
},
// 設置默認
setDefault: async function(_uid, default_id) {
// const default_id = !!isDefaults ? _id : '';
const MODEL = this.findOneAndUpdate({ _uid }, { default_id });
try {
const MB = await MODEL;
return { default_id }
} catch (error) {
console.log(error);
return error
}
},
};
return conn.model('account_mp_user_address', AccountUserAddressSchema)
}/**
* @name mongoDB update数组参数
*
*/
objToQuery(OBJ, KEY) {
return Object.keys(OBJ).reduce((a, b) => {
a[`${KEY}.$.${b}`] = OBJ[b];
return a
}, {});
}, 查看全部
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const { logger, helper } = app.createAnonymousContext();
const {
objToQuery
} = helper;
const conn = app.mongooseDB.get('mp');
const AccountUserAddressSchema = new Schema({
// 默认地址
default_id: {
type: Schema.Types.ObjectId,
default: null
},
// 用户id
_uid: {
type: Schema.Types.ObjectId
},
// 标签
tags: {
type: Array,
default: ['家', '公司', '学校']
},
// 地址列表
address: [{
// 收货人姓名
userName: {
type: String,
required: true
},
// 邮编
postalCode: {
type: String
},
// 省市
provinceName: {
type: String,
required: true
},
// 市
cityName: {
type: String,
required: true
},
// 区/县
countyName: {
type: String,
required: true
},
// 详细地址
detailInfo: {
type: String,
required: true
},
// 联系电话
telNumber: {
type: String,
required: true
},
// 状态 [[0,'删除'],[1,'正常']]
status: {
type: Number,
default: 1
},
// 标签
tag: String,
// 添加时间
addTime: {
type: Date,
default: new Date()
},
deleteTime: Date
}]
});
AccountUserAddressSchema.statics = {
// 添加
addOne: async function(_uid, BODYS) {
const { is_default } = BODYS;
const MODEL = this.findOneAndUpdate({
_uid
}, {
$push: {
'address': {...BODYS }
},
// ...isDefault && { default_id: _id }
}, {
new: true,
fields: 'cars default_id -_id'
});
try {
const RBD = await MODEL;
return !!RBD
} catch (error) {
console.log(error)
}
},
// 更新地址
updateOne: async function(_uid, _id, BODYS) {
// const { isDefault } = BODYS;
// delete BODYS.isDefault;
const MODEL = this.findOneAndUpdate({
_uid,
'address._id': _id
}, {
$set: {...objToQuery(BODYS, 'address') }
}, {
fields: 'address default_id -_id'
});
try {
// 修改数据
const DATAS = await MODEL;
// 修改默认
// !!isDefault && await this.setDefault(_uid, isDefault, _id);
return !!DATAS.address.length ? BODYS : { code: 211, message: '更新失败' }
} catch (error) {
return error
}
},
// 列表
list: async function(_uid) {
const MODEL = this.aggregate([{
$match: {
_uid: mongoose.Types.ObjectId(_uid)
}
}, {
$unwind: '$address'
}, {
$match: {
'address.deleteTime': { $exists: false }
}
}, {
$addFields: {
'address.isDefault': {
$eq: ['$default_id', '$address._id']
}
}
}, {
$replaceRoot: { newRoot: "$address" }
}]);
// const MODEL = this.find({ _uid })
try {
const RBD = await MODEL;
return RBD.length ? RBD : await this.initAddress(_uid)
} catch (error) {
console.log(error)
}
},
// 删除一个
delOne: async function(_uid, _id) {
const MODEL = this.findOneAndUpdate({
_uid,
'address._id': _id
}, {
'address.$.status': 0,
'address.$.deleteTime': new Date(),
});
try {
const RBD = await MODEL;
return { _id }
} catch (error) {

}
},
// 初始化用地址
initAddress: async function(_uid) {
const MODEL = this.create({ _uid: mongoose.Types.ObjectId(_uid) });
try {
const DATAS = await MODEL;
return DATAS
} catch (error) {
console.log(error)
}
},
// 获取单一数据
getOne: async function(_uid, _id) {
const MODEL = this.aggregate([{
$match: { _uid: mongoose.Types.ObjectId(_uid) }
}, {
$unwind: '$address'
}, {
$project: {
address: 1,
_id: 1,
default_id: 1,
}
}, {
$addFields: {
'address.isDefault': {
$eq: [{ $toString: '$default_id' }, _id]
}
}
}, {
$match: {
'address.deleteTime': { $exists: false },
'address._id': mongoose.Types.ObjectId(_id),
}
}, {
$replaceRoot: { newRoot: "$address" }
}]);
try {
if (_id !== "default") {
const DATAS = await MODEL;
return DATAS.length ? DATAS[0] : {}
}
} catch (error) {
console.log(error)
return error
}
},
// 获取默认地址
getDefault: async function(_uid) {
const MODEL = this.findOne({ _uid }, {}, {
fields: 'default_id -_id'
});
try {
const { default_id } = await MODEL;
return await this.getOne(_uid, default_id)
} catch (error) {
console.log(error);
return error
}
},
// 設置默認
setDefault: async function(_uid, default_id) {
// const default_id = !!isDefaults ? _id : '';
const MODEL = this.findOneAndUpdate({ _uid }, { default_id });
try {
const MB = await MODEL;
return { default_id }
} catch (error) {
console.log(error);
return error
}
},
};
return conn.model('account_mp_user_address', AccountUserAddressSchema)
}
/**
* @name mongoDB update数组参数
*
*/
objToQuery(OBJ, KEY) {
return Object.keys(OBJ).reduce((a, b) => {
a[`${KEY}.$.${b}`] = OBJ[b];
return a
}, {});
},

mongodb 分页封装(传统分页)【2020-10-30 修正】

mongodblopo1983 发表了文章 • 0 个评论 • 1503 次浏览 • 2020-09-22 11:47 • 来自相关话题

const pageFn = ({ MATCH = [], OTHERMATCH = [], OTHERFACET = {}, FACET_KEY = {}, limit = 20, page = 1 } = {}) => {
return [{
$facet: {
'list': [
...MATCH,
{
$skip: (page - 1) * limit
},
{
$limit: limit * 1
},
...OTHERMATCH.length ? OTHERMATCH : []
],
'page': [
...MATCH,
{
$count: 'count'
}
],
...OTHERFACET
}
}, {
$project: {
list: {
$cond: [{ $eq: [{ $size: '$list' }, 0] },
[], '$list'
]
},
page: {
$cond: [{ $eq: [{ $size: '$page' }, 0] },
[{ count: 0 }], '$page'
]
},
count: 1,
...FACET_KEY
}
}, {
$unwind: '$page'
}, {
$addFields: {
'page.limit': limit * 1,
'page.page': page * 1
}
}]
};
module.exports = pageFn 查看全部
const pageFn = ({ MATCH = [], OTHERMATCH = [], OTHERFACET = {}, FACET_KEY = {}, limit = 20, page = 1 } = {}) => {
return [{
$facet: {
'list': [
...MATCH,
{
$skip: (page - 1) * limit
},
{
$limit: limit * 1
},
...OTHERMATCH.length ? OTHERMATCH : []
],
'page': [
...MATCH,
{
$count: 'count'
}
],
...OTHERFACET
}
}, {
$project: {
list: {
$cond: [{ $eq: [{ $size: '$list' }, 0] },
[], '$list'
]
},
page: {
$cond: [{ $eq: [{ $size: '$page' }, 0] },
[{ count: 0 }], '$page'
]
},
count: 1,
...FACET_KEY
}
}, {
$unwind: '$page'
}, {
$addFields: {
'page.limit': limit * 1,
'page.page': page * 1
}
}]
};
module.exports = pageFn

linux 根据端口查进程id

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 1577 次浏览 • 2020-07-19 22:04 • 来自相关话题

netstat -tpln | grep [port]
kill [port]下面是windows的netstat -ano |findstr [port]
taskkill /f /t /im "进程id或者进程名称" 查看全部
netstat -tpln | grep [port]
kill [port]
下面是windows的
netstat -ano |findstr [port]
taskkill /f /t /im "进程id或者进程名称"

egg 自动同步关系型数据库model

Nodejslopo1983 发表了文章 • 0 个评论 • 1775 次浏览 • 2020-05-07 12:39 • 来自相关话题

// {app_root}/app.js
module.exports = app => {
app.beforeStart(async () => {
// 从配置中心获取 MySQL 的配置
// { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' }
await app.model.sync({ force: true });
});
}; 查看全部
// {app_root}/app.js
module.exports = app => {
app.beforeStart(async () => {
// 从配置中心获取 MySQL 的配置
// { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' }
await app.model.sync({ force: true });
});
};

centos7.x 防火墙常用操作

每天进步一点点lopo1983 发表了文章 • 0 个评论 • 1625 次浏览 • 2020-03-20 10:43 • 来自相关话题

1、开放端口firewall-cmd --zone=public --add-port=5672/tcp --permanent   # 开放5672端口firewall-cmd --zone=public --remove-port=5672/tcp --permanent  #关闭5672端口firewall-cmd --reload   # 配置立即生效

 

2、查看防火墙所有开放的端口firewall-cmd --zone=public --list-ports

 

3.、关闭防火墙

如果要开放的端口太多,嫌麻烦,可以关闭防火墙,安全性自行评估systemctl stop firewalld.service

 

4、查看防火墙状态 firewall-cmd --state

 

5、查看监听的端口netstat -lnpt
PS:centos7默认没有 netstat 命令,需要安装 net-tools 工具,yum install -y net-tools

 

 

6、检查端口被哪个进程占用netstat -lnpt |grep 5672

 

7、查看进程的详细信息

ps 6832

 

8、中止进程

kill -9 6832 查看全部
1、开放端口
firewall-cmd --zone=public --add-port=5672/tcp --permanent
   # 开放5672端口
firewall-cmd --zone=public --remove-port=5672/tcp --permanent 
 #关闭5672端口
firewall-cmd --reload
   # 配置立即生效

 

2、查看防火墙所有开放的端口
firewall-cmd --zone=public --list-ports


 

3.、关闭防火墙

如果要开放的端口太多,嫌麻烦,可以关闭防火墙,安全性自行评估
systemctl stop firewalld.service


 

4、查看防火墙状态
 firewall-cmd --state


 

5、查看监听的端口
netstat -lnpt

PS:centos7默认没有 netstat 命令,需要安装 net-tools 工具,yum install -y net-tools

 

 

6、检查端口被哪个进程占用
netstat -lnpt |grep 5672


 

7、查看进程的详细信息

ps 6832

 

8、中止进程

kill -9 6832