自学内容网 自学内容网

使用nest+typeorm框架写数据库导致mysql的binlog暴增记录

两天用nest+typeorm写了一个商城,上线后mysql日志binlog两天就达到了10几个G,排查结果如下:

有个功能是定时遍历所有未签收的订单,看看是否到了自动签收时间,如果到了,就把订单状态设置成已签收。

代码是这样的

//查找未签收的订单
const orderList = await this.orderRepo.find({where:{state:0)}})

for(let order of orderList){
//是否10天前的订单
    if(order.payTime<dayjs().addDays(-10,'days').unix()){
    //设置为自动签收
    order.state=2//签收状态
    order.signTime = dayjs().unix()
    await this.orderRepo.save(order)//保存订单
}else{//
    order.state=0 //保持未签收的状态
    await this.orderRepo.save(order)//保存订单
}
}

随着订单越来越多,导致每次执行 repo.save方法的时候,mysql都会将update的所有字段重新保存一次,导致binlog日志非常大,把阿里云默认的40G云盘两天就满了。

因为typeorm的save方法,会把每个字段都update更新一遍,这个方法最好在新增的时候使用,如果只是单纯更新某个字段,最好使用  update方法

await this.orderRepo.update(order.id,{state:order.state})//保存订单

 这样只会在binlog日志增加一行数据 update  order set state=1 where id = xxx


原文地址:https://blog.csdn.net/cangege123/article/details/142533026

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!