1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- /**
- * Created by PhpStorm.
- * User: wanggb
- * Date: 2019/1/10
- * Time: 10:14
- */
- namespace app\admin\command;
- use think\Config;
- use think\console\Command;
- use think\console\Input;
- use think\console\Output;
- use think\Db;
- use think\Log;
- use think\Request;
- class SaveRechargeLastId extends Command
- {
- const DB_NUM = 512; //数据库个数
- protected function configure()
- {
- $this->setName('SaveRechargeLastId')
- ->setDescription('记录所有分库中Recharge表中最后一条数据的ID');
- }
- protected function execute(Input $input, Output $output)
- {
- Request::instance()->module('admin');
- $output->writeln('开始获取分库ID');
- $i= 0;
- $arr = [];
- for ($idx = 0; $idx < self::DB_NUM; $idx++) {
- $i++;
- $db = $this->dbConnect($idx);
- $sql = "SELECT id FROM recharge order by id DESC LIMIT 1";
- $data = $db ->query($sql);
- if($data){
- $id = $data[0]['id'];
- }else{
- $id = 0;
- }
- $arr[$idx] = $id;
- Log::info('分库ID:'.$id.'ID:'.print_r($id, true));
- }
- $output->writeln(print_r(json_encode($arr),true));
- $file_name = ROOT_PATH.'runtime/log/'.date('Ym',time()).'/rechargeid'.date('YmdHi',time()).'.log';
- file_put_contents($file_name, print_r(json_encode($arr), true));
- $output->writeln('获取分库ID结束,总共'.$i.'个数据库');
- $output->writeln('文件存储路径:'.$file_name);
- }
- //链接数据库
- private function dbConnect($db_num)
- {
- $db_config = $this->charge_get_db_deploy($db_num);
- $db = Db::connect($db_config);
- return $db;
- }
- //分库 0-512
- private function charge_get_db_deploy($mod, $deploy = 'user')
- {
- $db = Config::get('db');
- $list = explode(';', $db[$deploy . '_list']);
- foreach ($list as $item) {
- $con = explode(':', $item); // 0=0-191库编号 1=192.168.1.149主IP 2=3306主端口 3=192.168.1.150从IP 4=3306从端口
- if (count($con) >= 3) {
- $c = explode('-', $con[0]); //库编号 0开始 1结束
- if (count($c) >= 2) {
- if ($c[0] <= $mod && $mod <= $c[1]) {
- $database = Config::get('database');
- if ($database['deploy'] == 1 && count($con) >= 5) { //开启主从 & 带主从配置
- $database['hostname'] = $con[1] . ',' . $con[3]; //192.168.1.149,192.168.1.150
- $database['hostport'] = $con[2] . ',' . $con[4]; //3306,3306
- } else { //只有主库
- $database['hostname'] = $con[1];
- $database['hostport'] = $con[2];
- }
- Log::info("分库获取成功 IP:{$database['hostname']} port: {$database['hostport']}");
- $database['database'] = str_replace('$mod', $mod, $db[$deploy . '_database']);
- return $database;
- }
- }
- }
- }
- Log::error("分库获取失败!");
- return [];
- }
- }
|