AutoRegetPortJob.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Http\Models\User;
  5. use App\Http\Models\Config;
  6. use Log;
  7. class AutoRegetPortJob extends Command
  8. {
  9. protected $signature = 'autoRegetPortJob';
  10. protected $description = '自动获取端口';
  11. public function __construct()
  12. {
  13. parent::__construct();
  14. }
  15. public function handle()
  16. {
  17. $config = $this->systemConfig();
  18. if ($config['auto_release_port']) {
  19. $userList = User::query()->where('status', '>=', 0)->where('enable', 1)->where('port', 0)->get();
  20. if (!$userList->isEmpty()) {
  21. foreach ($userList as $user) {
  22. $port = $config['is_rand_port'] ? $this->getRandPort() : $this->getOnlyPort();
  23. User::query()->where('id', $user->id)->update(['port' => $port]);
  24. }
  25. }
  26. }
  27. Log::info('定时任务:' . $this->description);
  28. }
  29. // 系统配置
  30. private function systemConfig()
  31. {
  32. $config = Config::query()->get();
  33. $data = [];
  34. foreach ($config as $vo) {
  35. $data[$vo->name] = $vo->value;
  36. }
  37. return $data;
  38. }
  39. // 获取一个随机端口
  40. public function getRandPort()
  41. {
  42. $config = $this->systemConfig();
  43. $port = mt_rand($config['min_port'], $config['max_port']);
  44. $deny_port = [1068, 1109, 1434, 3127, 3128, 3129, 3130, 3332, 4444, 5554, 6669, 8080, 8081, 8082, 8181, 8282, 9996, 17185, 24554, 35601, 60177, 60179]; // 不生成的端口
  45. $exists_port = User::query()->pluck('port')->toArray();
  46. if (in_array($port, $exists_port) || in_array($port, $deny_port)) {
  47. $port = $this->getRandPort();
  48. }
  49. return $port;
  50. }
  51. // 获取一个端口
  52. public function getOnlyPort()
  53. {
  54. $config = $this->systemConfig();
  55. $port = $config['min_port'];
  56. $deny_port = [1068, 1109, 1434, 3127, 3128, 3129, 3130, 3332, 4444, 5554, 6669, 8080, 8081, 8082, 8181, 8282, 9996, 17185, 24554, 35601, 60177, 60179]; // 不生成的端口
  57. $exists_port = User::query()->where('port', '>=', $config['min_port'])->where('port', '<=', $config['max_port'])->pluck('port')->toArray();
  58. while (in_array($port, $exists_port) || in_array($port, $deny_port)) {
  59. $port = $port + 1;
  60. }
  61. return $port;
  62. }
  63. }