Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

求指点nodejs用request大量发送post总是出现ETIMEDOUT

因为业务问题需要一直查询数据库发送post给各个网站,然后明明对方网站能ping通,能访问,但是总是报超时连接错误,有没有大佬原因帮忙看看,愿意付费
入口

const db = require('./db/sql');
const pc = require('./can/pc');

//定时回调  3次  第一次1分钟 第二次 2分钟 第三次5分钟
const sql = 'SELECT * from dong_order where  (huidiaocs<3 OR budan=1) and status = 1 and huidiao = 0';

// const batchPromise = async function (datas, asyncFunc, batchCnt = 5) {
//   // 最大批量操作数
//   const maxBatch = 1000;
//   if (batchCnt > maxBatch) {
//     batchCnt = maxBatch;
//   }
//   let tmpPromises = [];
//   for (let i = 0; i < datas.length; i++) {
//     tmpPromises.push(asyncFunc(datas[i]));
//     if ((i + 1) % batchCnt == 0 || i + 1 == datas.length) {
//       await Promise.all(tmpPromises);
//     }
//   }
// };

var waitDealQueue = {}
const dealOrder = async function (el) {
//   console.log(el.orderid)
     if(el.pid=="8041" && el.orderid=="KA22431761007762"){
  if (el.orderid in waitDealQueue) {
    return
  }
  const time2s = Math.round(new Date() / 1000);
  //当前时间戳
  if (el.huidiaocs == 0) {        //huidiaocs是回调次数 如果回调次数为0 则直接执行 huidiaotm是时间
    return pc.order(el.pid)
      .then(function (data) {
        if (data.length == 0) {
          console.log('商户不存在');
        } else {
          console.log("

===============发送回调===============");
          console.log("=给商户:" + el.pname + " ID:" + el.pid + "==");
          console.log("--单号:[" + el.orderid + "]-----");
          var signarr = pc.sign(el, data[0].miyao);
          var ps = pc.cpost(signarr, el.notify_url);
          return ps.then((s) => {
            // console.log(s);
            if (s.type == 1) {
              pc.Callback(el.id, JSON.stringify(signarr), s.data, time2s);    //更新订单
              console.log('订单' + el.orderid + '回调成功');
            } else if (s.type == 2) {
              pc.Callback2(el.id, JSON.stringify(signarr), s.data, time2s);
              console.log('订单' + el.orderid + '通知成功,但回调失败');
            }
          }).catch((s) => {
            console.log('订单' + el.orderid + '更新失败');
          });
        }
      })
      .catch((s) => {
        console.log('订单' + el.orderid + '更新失败');
      });
  } else {  //如果回调次数不为0
    waitDealQueue[el.orderid] = el.orderid
    console.log("

===============" + el.orderid + "加入延迟发送队列:延迟时间" + 5 * el.huidiaocs + "秒===============");
    setTimeout(() => {
      pc.order(el.pid)
        .then(function (data) {
          if (data.length == 0) {
            console.log('商户不存在');
          } else {
            console.log("

===============发送回调===============");
            console.log("=给商户:" + el.pname + " ID:" + el.pid + "==");
            console.log("--单号:[" + el.orderid + "]-----");
            var signarr = pc.sign(el, data[0].miyao);
            var ps = pc.cpost(signarr, el.notify_url);
            return ps.then((s) => {
              // console.log(s);
              if (s.type == 1) {
                pc.Callback(el.id, JSON.stringify(signarr), s.data, time2s);    //更新订单
                console.log('订单' + el.orderid + '回调成功');
              } else if (s.type == 2) {
                pc.Callback2(el.id, JSON.stringify(signarr), s.data, time2s);
                console.log('订单' + el.orderid + '通知成功,但回调失败');
              }
              delete waitDealQueue[el.orderid]
            })
          }
        })
        .catch((s) => {
          delete waitDealQueue[el.orderid]
          console.log('订单' + el.orderid + '更新失败');
        });
    }, 5000 * el.huidiaocs)

  }

     }
};

function huidiao () {
  return new Promise((reslove, reject) => {
    db.query(sql, function (err, rows, fields) {
      if (err) {
        console.log(err);
        reslove()
        return;
      }
      const time = Math.round(new Date() / 1000); //当前时间戳
      console.log('查询到:' + rows.length + '条数据');
      let cnt = 0
      for (let i = 0; i < rows.length; i++) {
        dealOrder(rows[i]).then(() => {
          cnt++
          if (cnt == rows.length) {
            reslove()
          }
        }).catch(() => {
          cnt++
          reslove()
        })
      }
    });
  })
}
//t监控时间
async function start (t) {
  console.log('============订单监控============');
  const time = t * 1000;
  for (; ;) {
    await huidiao()
    sleep(time)
  }
}

function sleep (time) {
  var startTime = new Date().getTime() + parseInt(time, 10);
  while (new Date().getTime() < startTime) { }
}
start(4.5)

post发送模块

const db = require('../db/sql');
const md5 = require("md5");
const request = require("request");

module.exports = {
    order:function(pid){                //获取商户数据
        const sql = 'SELECT miyao from dong_user where id ='+pid;
        return new Promise(function(resolve, reject){
            db.query(sql, function(err, rows, fields){
                if(err){
                    reject(err); 
                }
                resolve(rows);
            })
        })
    },
    sign:function(data,mi){            //生成数组
        var arr = 'miyao='+mi+'&money='+data.money+'&order='+data.orderid+'&out_order='+data.out_trade_no+'&sid='+data.pid+'&status=TRADE_SUCCESS';
        var sign = md5(arr);
        qmsz = {
            "money" : data.money,
            "paytype" : data.type,
            "name" : data.name,
            "order" : data.orderid,
            "out_order" : data.out_trade_no,
            "sid" : data.pid,
            "status" : "TRADE_SUCCESS",
            "date" :  Math.round(new Date() / 1000),
            "sign" : sign,
       }
       return qmsz;
    },
    cpost: function(data,url,callback){
        // console.log("访问数据:"+data.order);
        //console.log("访问url:"+url);
        // console.log(content);
        // var data=JSON.stringify(data); 
        // console.log(data);
        return new Promise(function(res,rej){
            request(
                {
                  url: url,
                  method: 'POST',
                  json: true,
                  timeout: 5000,
                  requestCert: true,
                  headers: {
                    'content-type': 'application/json',
                    // "User-Agent": "request/2.88.2"
                  },
                //   body: data,
                  body: JSON.stringify(data),
                },
                function (error, response, body) {
                    console.log("-------------");
                    
                    // console.log(response);
                    console.log(body)
                    if(!error) {
                        console.log(response.statusCode)
                        if (JSON.stringify(body || {}).toLocaleLowerCase().indexOf('success') != -1) {
                            datas = {
                                "type": 1,
                                "data": body
                            };
                            res(datas);
                        } else {
                            datas = {
                                "type": 2,
                                "data": body
                            };
                            res(datas);
                        }
                    } else {
                        console.log(error);
                        // console.log("111");
                        rej(-1);
                    }
                }
              );
        })
    },
    Callback:function(id,qcdata,hddata,time){           //根据id 更新请求参数  添加回调参数
        // const time = Math.round(new Date() / 1000);     //当前时间戳
        return new Promise(function(res,rej){
            const sql = `UPDATE dong_order set huidiaocs=huidiaocs+1,huidiao='1',shdata='${qcdata}',huidiaotm='${time}',budan=0,shhddata='${hddata}' where id =${id}`;
            db.query(sql, function(err, rows, fields){
                if(err){
                    rej(err); 
                }
                res(rows);
            })
        })
    },
    Callback2:function(id,qcdata,hddata,cs,time){          //请求失败返回数据
        // const time = Math.round(new Date() / 1000);
        return new Promise(function(res,rej){
            const sql = `UPDATE dong_order set huidiaocs=huidiaocs+1,shdata='${qcdata}',huidiaotm='${time}',budan=0,shhddata='${hddata}' where id =${id}`;
            db.query(sql, function(err, rows, fields){
                if(err){
                    rej(err); 
                }
                res(rows);
            })
        })
    },
    
    lstop:function(id,s){
        return new Promise(function(res,rej){
            const sql = `UPDATE dong_mashanghaochi set jiedan='${s}' where username = "${id}"`;
            db.query(sql, function(err, rows, fields){
                if(err){
                    rej(err); 
                }
                res(rows);
            })
        })
    },
    lstopor:function(id,s){
        return new Promise(function(res,rej){
            const sql = `UPDATE dong_order set chaoshi='${s}' where id =${id}`;
            db.query(sql, function(err, rows, fields){
                if(err){
                    rej(err); 
                }
                res(rows);
            })
        })
    },

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. 换个别的地址试一下?https://www.lilnong.top/cors/sf-1010000037564343
  2. 如果还是有问题,增加一个重试的策略。同时,timeout改的稍微大一点10s或者20s这样。避免因为你的网络有问题造成超时。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...