ReadRecordPersistence.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Redis;
  5. use DB;
  6. class ReadRecordPersistence extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'ReadRecordPersistence';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Command description';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return mixed
  33. */
  34. public function handle()
  35. {
  36. $this->saveDB();
  37. }
  38. private function saveDB(){
  39. $result = $this->compactData();
  40. if(!$result){
  41. return ;
  42. }
  43. foreach ($result as $key=>$v){
  44. $table = sprintf('record_records%s',$key);
  45. DB::connection('read_record_mysql')->table($table)->insert($v);
  46. }
  47. }
  48. private function getRecord(){
  49. $length = Redis::Llen('ReadRecordStats');
  50. if(!$length) return [];
  51. $count = ceil($length/200);
  52. $result = [];
  53. for ($i=0;$i <$count;$i++){
  54. $start = $i*200;
  55. $end = $start+199;
  56. $result[] = Redis::Lrange('ReadRecordStats',$start,$end);
  57. }
  58. Redis::del('ReadRecordStats');
  59. return $result;
  60. }
  61. private function compactData(){
  62. $data = $this->getRecord();
  63. if(!$data){
  64. return [];
  65. }
  66. $result = [];
  67. foreach ($data as $item){
  68. foreach ($item as $v){
  69. $record = json_decode($v,1);
  70. $table = $record['uid']%2048;
  71. $result[$table][] = $record;
  72. }
  73. }
  74. return $result;
  75. }
  76. }