首页 > 编程语言 >ThinkPHP6定时任务同步千万级流水数据

ThinkPHP6定时任务同步千万级流水数据

时间:2024-08-22 14:27:28浏览次数:6  
标签:同步 tblName Db 千万级 id value 定时 ThinkPHP6 sourceData

ThinkPHP6定时任务同步千万级流水数据

多数据源配置

自定义指令

<?php
declare (strict_types = 1);

namespace app\command\SyncDtaTask;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Db;

/**
 * 分批同步数据
 */
class DevLogSyncCmd extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('DevLogSyncCmd')
            ->setDescription('分批次同步流水数据');
    }

    protected function execute(Input $input, Output $output)
    {
        $tableList = [
            'dev_log',
        ];
        //$citys = Db::query('SELECT id FROM city');
        //同步城市固定写死
        $citys = [37];
        foreach ($tableList as $item) {
            foreach ($citys as $city) {
                // 检查今年的流水表
                $todayTable = date('Y');
                $tblName = "{$item}_{$city}_{$todayTable}";
                $res = Db::execute("show tables like '{$tblName}'");
                if ($res === 0) {
                    $output->writeln('补建流水表'.$item.'_'.$city['id'].'_'.$todayTable);
                    Db::execute("create table {$tblName} like {$item}");
                }

                // 获取源数据库和目标数据库的连接
                $sourceDb = Db::connect("source1");
                $targetDb = Db::connect();

                //获取待同步最大值,现从目的数据库中获取
                $maxSyncedIdResult = $targetDb->query("SELECT MAX(id) as max_id FROM {$tblName}");
                //如果没获取到,则取源数据库的最大ID
                $maxSyncedId = $maxSyncedIdResult[0]['max_id'] ?? 0;
                if (!$maxSyncedId){
                    $maxSyncedIdResult = $sourceDb->query("SELECT MAX(id) as max_id FROM {$tblName}");
                    $maxSyncedId = ($maxSyncedIdResult[0]['max_id'] ?? 0) - 10000;
                }

                // 获取源库中的数据
                $sourceData = $sourceDb->query("SELECT * FROM {$tblName} WHERE id > {$maxSyncedId} ORDER BY id desc LIMIT 1000");
                //方案一: 直接使用插入方法
                //$targetDb->name($tblName)->insertAll($sourceData);

                //方案二: 需要处理字段
                if (!empty($sourceData)) {
                    // 准备插入语句
                    $insertQuery = "INSERT INTO {$tblName} (" . implode(", ", array_keys($sourceData[0])).",flag" . ") VALUES ";

                    // 准备参数绑定的占位符和值
                    $insertValues = [];
                    $params = [];
                    foreach ($sourceData as $index => $row) {
                        $rowValues = [];
                        foreach ($row as $key => $value) {
                            //$paramKey = ":{$key}_{$index}";
                            //$params[$paramKey] = $value;
                            $rowValues[] = !empty($value)?"'".$value."'":"null";
                        }
                        $insertValues[] = "(" . implode(", ", $rowValues) .",1" . ")";
                    }
                    //每一行的value值用逗号分割
                    $insertQuery .= implode(", ", $insertValues);

                    // 执行插入操作
                    $targetDb->execute($insertQuery);

                    $output->writeln("已同步 " . count($sourceData) . " 条记录到 {$tblName}。");
                } else {
                    $output->writeln("没有需要同步的数据。");
                }

            }
        }
    }
}

设置定时任务

标签:同步,tblName,Db,千万级,id,value,定时,ThinkPHP6,sourceData
From: https://www.cnblogs.com/aeolian/p/18373757

相关文章

  • .NetCore里使用定时任务BackgroundService
    原文链接:https://blog.csdn.net/x1234w4321/article/details/140797306namespaceXCGWebApp.TimerService{///<summary>///后台定时任务///</summary>publicclassTimerBackgroundService:BackgroundService{protectedoverrid......
  • 仿Muduo库实现高并发服务器——任务定时器模块
    任务定时器模块TimerWheel在本项目中的简单使用:        下面这张图是channel模块,poller模块,TimerWheel模块,EventLoop模块,LoopThreadPool模块进行组合。便于大家对这个项目的理解,因为代码看起来挺复杂的。上面右下角就是定时器模块。TimerTask类的实现:usingTaskF......
  • Mac导出Mysql千万级表数据
    MysqlDumpmysqldump-h[服务器地址]-u[用户名]-p[密码]--single-transaction--quick[数据库名][表名]>[导出文件.sql]•--single-transaction保证了数据的一致性,并且不会在导出期间锁定表(只针对InnoDB有效)。•--quick选项进一步减少了内存使用,因为它逐行导出数......
  • VS2022+QT6.7.2 定时器的使用(两种方法)
    目录一、继承QObject定时器事件二、QTimer类三、具体实现一、继承QObject定时器事件  所有继承自QObject的类,都会有一个timerEvent(QTimerEvent*event)的纯虚函数,startTimer()设定定时间隔并启动,再重载这个函数以处理自己的定时任务,多个定时任务用timeId区分,结束后......
  • python apscheduler定时任务处理
    ApschedulerApscheduler是一个基于Quartz的python定时任务框架,提供了基于日期、固定时间间隔以及corntab类型的任务,并且可持久化任务。安装apscheduler依赖库pipinstallapschedulerAPScheduler组件:schedulers-调度器triggers-触发器jobstores-作业存储器exec......
  • python flask 定时器
    安装pipinstallflaskpipinstallflask_apscheduler-ihttps://pypi.tuna.tsinghua.edu.cn/simple/--trusted-hostpypi.tuna.tsinghua.edu.cn使用方法一:使用Config类配置时间规则fromflaskimportFlaskfromflask_apschedulerimportAPSchedulerclassC......
  • 定时器
    定时器是一个应用十分广泛的线程工具,可用于调度多个定时任务以后台线程的方式执行。在Java中,可以通过Timer和TimerTask类来实现定义调度的功能TimerpublicTimer()publicvoidschedule(TimerTask task,long delay)publicvoidschedule(TimerTasktask,longdelay,longpe......
  • 控制台程序定时重启
    调用if(!System.Diagnostics.Debugger.IsAttached){    inttimes=24*3600;    自动重启(times);}privatestaticvoid自动重启(inttimes){    newSystem.Timers.Timer(times*1000)    {        Enabled=true,        Aut......
  • postgresql 定时收集表和索引统计信息 转发:https://blog.csdn.net/weixin_33711641/a
    --由于pg中表和索引的信息收集都是基于时间点的,对于以往的信息无法与现在的信息进行对比,故写下此工具进行统计信息收集--创建数据信息的schemacreateschemadb_stat;--创建收集信息的基础表createtabledb_stat.snapshot_pg_stat_all_indexes(relidint,indexrelidint,scheman......
  • STP(角色选举、状态、定时器、拓扑变更机制、PVST、PVST+增强特性)
    文章目录一、什么是STP定义特点工作原理专业术语二、STP角色选举1、配置命令:2、端口角色:三、STP的状态四、STP的定时器①HelloTime:2s②MaxAge:20s③ForwardDelay:15s④AgingTime:300s五、STP拓扑变化机制六、PVST七、PVST+增强特性......