SaveRechargeLastId.php 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: wanggb
  5. * Date: 2019/1/10
  6. * Time: 10:14
  7. */
  8. namespace app\admin\command;
  9. use think\Config;
  10. use think\console\Command;
  11. use think\console\Input;
  12. use think\console\Output;
  13. use think\Db;
  14. use think\Log;
  15. use think\Request;
  16. class SaveRechargeLastId extends Command
  17. {
  18. const DB_NUM = 512; //数据库个数
  19. protected function configure()
  20. {
  21. $this->setName('SaveRechargeLastId')
  22. ->setDescription('记录所有分库中Recharge表中最后一条数据的ID');
  23. }
  24. protected function execute(Input $input, Output $output)
  25. {
  26. Request::instance()->module('admin');
  27. $output->writeln('开始获取分库ID');
  28. $i= 0;
  29. $arr = [];
  30. for ($idx = 0; $idx < self::DB_NUM; $idx++) {
  31. $i++;
  32. $db = $this->dbConnect($idx);
  33. $sql = "SELECT id FROM recharge order by id DESC LIMIT 1";
  34. $data = $db ->query($sql);
  35. if($data){
  36. $id = $data[0]['id'];
  37. }else{
  38. $id = 0;
  39. }
  40. $arr[$idx] = $id;
  41. Log::info('分库ID:'.$id.'ID:'.print_r($id, true));
  42. }
  43. $output->writeln(print_r(json_encode($arr),true));
  44. $file_name = ROOT_PATH.'runtime/log/'.date('Ym',time()).'/rechargeid'.date('YmdHi',time()).'.log';
  45. file_put_contents($file_name, print_r(json_encode($arr), true));
  46. $output->writeln('获取分库ID结束,总共'.$i.'个数据库');
  47. $output->writeln('文件存储路径:'.$file_name);
  48. }
  49. //链接数据库
  50. private function dbConnect($db_num)
  51. {
  52. $db_config = $this->charge_get_db_deploy($db_num);
  53. $db = Db::connect($db_config);
  54. return $db;
  55. }
  56. //分库 0-512
  57. private function charge_get_db_deploy($mod, $deploy = 'user')
  58. {
  59. $db = Config::get('db');
  60. $list = explode(';', $db[$deploy . '_list']);
  61. foreach ($list as $item) {
  62. $con = explode(':', $item); // 0=0-191库编号 1=192.168.1.149主IP 2=3306主端口 3=192.168.1.150从IP 4=3306从端口
  63. if (count($con) >= 3) {
  64. $c = explode('-', $con[0]); //库编号 0开始 1结束
  65. if (count($c) >= 2) {
  66. if ($c[0] <= $mod && $mod <= $c[1]) {
  67. $database = Config::get('database');
  68. if ($database['deploy'] == 1 && count($con) >= 5) { //开启主从 & 带主从配置
  69. $database['hostname'] = $con[1] . ',' . $con[3]; //192.168.1.149,192.168.1.150
  70. $database['hostport'] = $con[2] . ',' . $con[4]; //3306,3306
  71. } else { //只有主库
  72. $database['hostname'] = $con[1];
  73. $database['hostport'] = $con[2];
  74. }
  75. Log::info("分库获取成功 IP:{$database['hostname']} port: {$database['hostport']}");
  76. $database['database'] = str_replace('$mod', $mod, $db[$deploy . '_database']);
  77. return $database;
  78. }
  79. }
  80. }
  81. }
  82. Log::error("分库获取失败!");
  83. return [];
  84. }
  85. }