nodejs之连接redis以及事务封装与使用

版权声明:转载请注明出处 https://blog.csdn.net/wushichao0325/article/details/83930819

简介

本文章主要针对nodejs中redis数据库模块事务的封装,此文章只涉及本人个人见解和使用习惯,如果你还有更好的方法,欢迎提出一起交流。

所需模块

目前redis模块是使用回调函数的形式来接受返回的数据,这样无疑会导致多种嵌套的使用,所以我们利用bluebird模块进行加工变成promise,来美观代码:

  1. redis :V^2.8.0;
  2. bluebird:V^3.5.2;

文件结构

  1. config:redis.json(redis的连接参数)
  2. db:redis.js(连接redis)
  3. model:RedisModel.js(对于redis的一些操作的封装)
    4.cache:CacheOrders.js(针对订单相关操作的封装,其中使用redismodel.js的方法)

干货部分

话不多少,只有代码才能说明一切。

1 此部分为redis初始化配置信息:

// config文件下的redis.json
{
  "host":"127.0.0.1",
  "port":6379,
  "db":0,
  "password":"*******"
}

2 数据库连接

//db文件下的redis.js
var redis=require('redis');
var redisConfig=require('../config/redis');
const utils=require('../utils/index')();
const logger=utils.logger;

redisConfig.retry_strategy= function (options) {
    if (options.error && options.error.code === 'ECONNREFUSED') {
        // End reconnecting on a specific error and flush all commands with
        // a individual error
        return new Error('The server refused the connection');
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
        // End reconnecting after a specific timeout and flush all commands
        // with a individual error
        return new Error('Retry time exhausted');
    }
    if (options.attempt > 10) {
        // End reconnecting with built in error
        return undefined;
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000);
};
//在redis中的操作为原子操作,就算是异步操作,他也是按照代码顺序一条一条执行
//创建一个client连接到redis server数据库
function startRedis(){
    var client=redis.createClient(redisConfig);
    //事件
    client.on("ready",function(){
        logger.info("redis opened success");
    });
    //监听error事件,可以是redis客户端自动连接数据库
    client.on("error", function (err) {
        logger.error("数据库断开",err);
    });
    //服务器与数据库断开连接
    client.on("end", function () {
        logger.warn("与数据开断开连接");
    });
    return client;
}


module.exports={
    startRedisDb:startRedis
};

3 RedisModel的封装和对数据库的使用

//因为项目需要,选择redis中的List表结构存储数据
const redis=require('../db/redis');
const client=redis.startRedisDb();
const Promise = require('bluebird');
//列表
//向redis中插入整个数组,其数组中为多条string类型的json数据
function setList(listId,list){//添加整个数组
    for(let i=0;i<list.length;i++){
        if((typeof list[i])==="object"){
            list[i]=JSON.stringify(list[i]);
        }
    }
    client.lpush(listId,list[0]);
    for(let i=1;i<list.length;i++){
        client.rpush(listId,list[i]);
    }
    //cb(null,"set success");
    return true;
}
//向表中插入单条数据
function pushList(listId,value,cb){//添加单个数据
    client.rpush(listId,value,function(err,replay){
        if(err){
            cb(err,null);
        }else {
            cb(null,replay);
        }
    });
    
}
//删除指定的元素
function removeListByValue(listId,value,cb){

    client.lrem(listId,1,value,function(err,data){
        if(data){
            cb(null,data);
        }else{
            cb(err,null)
        }
    });
}
//更新redis中的指定元素
function updateListValueByIndex(listId,index,newValue,cb){
    newValue=JSON.stringify(newValue);
    client.lset(listId,index,newValue,function(err,data){
        if(err){
            cb(err,null);
        }else{
            cb(null,data);
        }
    })
}
//向指定位置插入元素
function insertValueByIndex(listId,value,index,cb){
    index=Number(index);
    if(index===0){
        client.lindex(listId,index,function(err,result){
            client.linsert(listId,"BEFORE",result,value,function(err,replay){
                if(err){
                    cb(err,null);
                }else {
                    cb(null,replay);
                }
            })
        });
    }else{
        client.lindex(listId,index-1,function(err,result){
            client.linsert(listId,"AFTER",result,value,function(err,replay){
                if(err){
                    cb(err,null);
                }else {
                    cb(null,replay);
                }
            })
        });
    
    }  
}
//根据下标获取表中的指定数据
function getValueByIndex(listId,index,cb){
    client.lindex(listId,index,function(err,data){
        if(err){
            cb(err,null);
        }else{
            cb(null,data);
        }
    })
}
//查询指定范围的数据
function getListByRange(listId,begin,end,cb){
    client.lrange(listId,begin,end, function (err,data) {
        if(err){
            cb(err,null);
        }else {
            cb(null,data);
        }
    });
}
//删除整个表
function deleteKey(key,cb){
    client.del(key, function (err,data) {
        if(err){
            cb(err,null);
        }else {
            cb(null,data);
        }
    })
}
//使用redis事务
function insertListTransaction(functions,cb){
    //functions=[client.multi(),rpush(),rpush(),rpush()]//为多条redis的执行语句,其中multi和exec为事务的开启和结束标志。
    client.multi(functions).exec(function(err,replies){
        if(err){
            cb(err,null);
        }else{
            cb(null,replies);
        }
    })
}
module.exports={
    setList:setList,
    pushList:pushList,
    removeListByValue:removeListByValue,
    updateListValueByIndex:updateListValueByIndex,
    insertValueByIndex:insertValueByIndex,
    getValueByIndex:getValueByIndex,
    getListByRange:getListByRange,
    deleteKey:deleteKey,
    insertListTransaction:insertListTransaction
};


4 模型的封装

//cache文件下CacheOrders.js
class CacheOrders{
    constructor(){
        this.orders={};//根据用户分类的订单
        this.ordersList=[];
    }
    //同时插入订单和订单项,当有一步操作失败时,撤销所有操作即使用了redis的事务机制
    async insertCacheOrderAndOrderItem(order,orderItem){
        var insertListTransaction=Promise.promisify(RedisModel.insertListTransaction,{context:RedisModel});
        order=JSON.stringify(order);
        orderItem=JSON.stringify(orderItem);
        let addOrder_result;
        try{
            addOrder_result=await insertListTransaction("orders","orderItems",order,orderItem);
            await this.refreshCache();
        }catch(e){
            console.log(e);
            addOrder_result=null;
        }
        return addOrder_result;
    }
}

具体使用

let CacheOrders=require(../cache/CacheOrders.js)
let orderJson={
    oid:orderInfo.oid,
    onumber:orderInfo.onumber,
    oaccount:orderInfo.oaccount,
    recipient:orderInfo.recipient,
    district:orderInfo.district,
    phone:orderInfo.phone,
    express:orderInfo.express,
    ordertime:orderInfo.ordertime,
    paytime:orderInfo.paytime,
    state:orderInfo.state,
    uid:orderInfo.uid,
    detaildistrict:orderInfo.detaildistrict
}
let orderItemJson={
    oitemid:orderInfo.oitemid,
    oid:orderInfo.oid,
    pcount:orderInfo.pcount,
    pid:orderInfo.pid,
    sid:orderInfo.sid,
    buysource:orderInfo.buysource,
    fromuid:orderInfo.fromuid,
    essayuid:orderInfo.essayuid,
    standard:orderInfo.standard,
    phy_number:"null"
    phy_state:-1
}
let insert_result=await cacheOrders.insertCacheOrderAndOrderItem(orderJson,orderItemJson);
if(insert_result==null){
    logger.info("添加订单失败");
    res.send({encode:-1,msg:"添加订单失败"});
}else{
	res.send({encode:0,msg:"添加订单成功"});
}

到这里我们就结束了,如果你喜欢,那谢谢你的浏览,如果不喜欢,那请留下你的建议。

如果有nodejs志同道合的人,欢迎加q:823522370,一起进步。

猜你喜欢

转载自blog.csdn.net/wushichao0325/article/details/83930819