thinkphp5.1运行workerman出现Cannot use Workerman\Worker as Worker because the name is already in use错误

这是因为命名空间冲突导致的错误。
修改方法:

1.找到文件:
\vendor\topthink\think-worker\src\command\Server.php
 
找到命名空间:
use Workerman\Worker;
修改为:
use Workerman\Worker as Worker2;
紧接着修改 75,97,108, 119 行与 126的 worker 改为 Worker2
 
 
2.找到文件:
\vendor\topthink\think-worker\src\command\GatewayWorker.php
 
找到命名空间
use Workerman\Worker;
修改为:
use Workerman\Worker as Worker3;

下面是我已经修改好的,可以直接用我修改好的这两个文件替换掉原来的
\vendor\topthink\think-worker\src\command\Server.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think\worker\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use think\facade\Env;
use think\worker\Server as WorkerServer;
use Workerman\Worker as Worker2;

/**
 * Worker Server 命令行类
 */

class Server extends Command
{
    protected $config = [];

    public function configure()
    {
        $this->setName('worker:server')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null)
            ->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null)
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
            ->setDescription('Workerman Server for ThinkPHP');
    }

    public function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');

        if (DIRECTORY_SEPARATOR !== '\') {
            if (!in_array($action, ['
start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
                $output->writeln("<error>Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .</error>");
                return false;
            }

            global $argv;
            array_shift($argv);
            array_shift($argv);
            array_unshift($argv, '
think', $action);
        } elseif ('
start' != $action) {
            $output->writeln("<error>Not Support action:{$action} on Windows.</error>");
            return false;
        }

        $this->config = Config::pull('
worker_server');

        if ('
start' == $action) {
            $output->writeln('
Starting Workerman server...');
        }

        // 自定义服务器入口类
        if (!empty($this->config['
worker_class'])) {
            $class = (array) $this->config['
worker_class'];

            foreach ($class as $server) {
                $this->startServer($server);
            }

            // Run worker
            Worker2::runAll();
            return;
        }

        if (!empty($this->config['
socket'])) {
            $socket            = $this->config['
socket'];
            list($host, $port) = explode('
:', $socket);
        } else {
            $host     = $this->getHost();
            $port     = $this->getPort();
            $protocol = !empty($this->config['
protocol']) ? $this->config['protocol'] : 'websocket';
            $socket   = $protocol . '
://' . $host . ':' . $port;
            unset($this->config['host'], $this->config['port'], $this->config['protocol']);
        }

        if (isset($this->config['context'])) {
            $context = $this->config['context'];
            unset($this->config['context']);
        } else {
            $context = [];
        }

        $worker = new Worker2($socket, $context);

        if (empty($this->config['pidFile'])) {
            $this->config['pidFile'] = Env::get('runtime_path') . 'worker.pid';
        }

        // 避免pid混乱
        $this->config['pidFile'] .= '_' . $port;

        // 开启守护进程模式
        if ($this->input->hasOption('daemon')) {
            Worker2::$daemonize = true;
        }

        if (!empty($this->config['ssl'])) {
            $this->config['transport'] = 'ssl';
            unset($this->config['ssl']);
        }

        // 设置服务器参数
        foreach ($this->config as $name => $val) {
            if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) {
                Worker2::${$name} = $val;
            } else {
                $worker->$name = $val;
            }
        }

        // Run worker
        Worker2::runAll();
    }

    protected function startServer($class)
    {
        if (class_exists($class)) {
            $worker = new $class;
            if (!$worker instanceof WorkerServer) {
                $this->output->writeln("<error>Worker Server Class Must extends \\think\\worker\\Server</error>");
            }
        } else {
            $this->output->writeln("<error>Worker Server Class Not Exists : {$class}</error>");
        }
    }

    protected function getHost()
    {
        if ($this->input->hasOption('host')) {
            $host = $this->input->getOption('host');
        } else {
            $host = !empty($this->config['host']) ? $this->config['host'] : '0.0.0.0';
        }

        return $host;
    }

    protected function getPort()
    {
        if ($this->input->hasOption('port')) {
            $port = $this->input->getOption('port');
        } else {
            $port = !empty($this->config['port']) ? $this->config['port'] : 2345;
        }

        return $port;
    }
}

\vendor\topthink\think-worker\src\command\GatewayWorker.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think\worker\command;

use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Config;
use Workerman\Worker as Worker3;

/**
 * Worker 命令行类
 */

class GatewayWorker extends Command
{
    public function configure()
    {
        $this->setName('worker:gateway')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('host', 'H', Option::VALUE_OPTIONAL, 'the host of workerman server.', null)
            ->addOption('port', 'p', Option::VALUE_OPTIONAL, 'the port of workerman server.', null)
            ->addOption('daemon', 'd', Option::VALUE_NONE, 'Run the workerman server in daemon mode.')
            ->setDescription('GatewayWorker Server for ThinkPHP');
    }

    public function execute(Input $input, Output $output)
    {
        $action = $input->getArgument('action');

        if (DIRECTORY_SEPARATOR !== '\') {
            if (!in_array($action, ['
start', 'stop', 'reload', 'restart', 'status', 'connections'])) {
                $output->writeln("Invalid argument action:{$action}, Expected start|stop|restart|reload|status|connections .");
                exit(1);
            }

            global $argv;
            array_shift($argv);
            array_shift($argv);
            array_unshift($argv, '
think', $action);
        } else {
            $output->writeln("GatewayWorker Not Support On Windows.");
            exit(1);
        }

        if ('
start' == $action) {
            $output->writeln('
Starting GatewayWorker server...');
        }

        $option = Config::pull('
gateway_worker');

        if ($input->hasOption('
host')) {
            $host = $input->getOption('
host');
        } else {
            $host = !empty($option['
host']) ? $option['host'] : '0.0.0.0';
        }

        if ($input->hasOption('
port')) {
            $port = $input->getOption('
port');
        } else {
            $port = !empty($option['
port']) ? $option['port'] : '2347';
        }

        $this->start($host, $port, $option);
    }

    /**
     * 启动
     * @access public
     * @param  string   $host 监听地址
     * @param  integer  $port 监听端口
     * @param  array    $option 参数
     * @return void
     */
    public function start($host, $port, $option = [])
    {
        $registerAddress = !empty($option['
registerAddress']) ? $option['registerAddress'] : '127.0.0.1:1236';

        if (!empty($option['
register_deploy'])) {
            // 分布式部署的时候其它服务器可以关闭register服务
            // 注意需要设置不同的lanIp
            $this->register($registerAddress);
        }

        // 启动businessWorker
        if (!empty($option['
businessWorker_deploy'])) {
            $this->businessWorker($registerAddress, isset($option['
businessWorker']) ? $option['businessWorker'] : []);
        }

        // 启动gateway
        if (!empty($option['
gateway_deploy'])) {
            $this->gateway($registerAddress, $host, $port, $option);
        }

        Worker3::runAll();
    }

    /**
     * 启动register
     * @access public
     * @param  string   $registerAddress
     * @return void
     */
    public function register($registerAddress)
    {
        // 初始化register
        new Register('
text://' . $registerAddress);
    }

    /**
     * 启动businessWorker
     * @access public
     * @param  string   $registerAddress registerAddress
     * @param  array    $option 参数
     * @return void
     */

    public function businessWorker($registerAddress, $option = [])
    {
        // 初始化 bussinessWorker 进程
        $worker = new BusinessWorker();

        $this->option($worker, $option);

        $worker->registerAddress = $registerAddress;
    }

    /**
     * 启动gateway
     * @access public
     * @param  string   $registerAddress registerAddress
     * @param  string   $host 服务地址
     * @param  integer  $port 监听端口
     * @param  array    $option 参数
     * @return void
     */

    public function gateway($registerAddress, $host, $port, $option = [])
    {
        // 初始化 gateway 进程
        if (!empty($option['socket'])) {
            $socket = $option['socket'];
            unset($option['socket']);
        } else {
            $protocol = !empty($option['protocol']) ? $option['protocol'] : 'websocket';
            $socket   = $protocol . '://' . $host . ':' . $port;
            unset($option['host'], $option['port'], $option['protocol']);
        }

        $gateway = new Gateway($socket, isset($option['context']) ? $option['context'] : []);

        // 以下设置参数都可以在配置文件中重新定义覆盖
        $gateway->name                 = 'Gateway';
        $gateway->count                = 4;
        $gateway->lanIp                = '127.0.0.1';
        $gateway->startPort            = 2000;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"ping"}';
        $gateway->registerAddress      = $registerAddress;

        // 全局静态属性设置
        foreach ($option as $name => $val) {
            if (in_array($name, ['stdoutFile', 'daemonize', 'pidFile', 'logFile'])) {
                Worker3::${$name} = $val;
                unset($option[$name]);
            }
        }

        $this->option($gateway, $option);
    }

    /**
     * 设置参数
     * @access protected
     * @param  Worker   $worker Worker对象
     * @param  array    $option 参数
     * @return void
     */

    protected function option($worker, array $option = [])
    {
        // 设置参数
        if (!empty($option)) {
            foreach ($option as $key => $val) {
                $worker->$key = $val;
            }
        }
    }

}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: