在您描述的示例(调整图像大小)中,您基本上在调整图像大小所需的时间内保持 Apache 连接打开。 Apache 进程很昂贵,为了使您的系统尽可能可扩展,您应该尽可能缩短 Web 请求/响应时间。
另一个想法是使用队列可以控制并发性。如果 100 多个用户同时上传图片以调整大小怎么办?您的服务器可以处理吗?如果您有一个工作(后端)服务器来处理这些请求,那么您将能够只允许执行 X 个并发作业。
同样适用于 Web 服务请求:不是让连接保持打开状态,而是基本上将 Web 服务调用的执行卸载到工作进程,这释放了 Apache 进程,并且您可以实现 AJAX 轮询机制检查后端服务器向 web 服务发出的请求是否完成。从长远来看,系统的扩展性会更好,用户通常不喜欢等待操作完成而没有关于操作位置的反馈。队列允许您异步执行任务并向访问者提供有关任务完成状态的反馈。
2- 您的 Controller 文件夹中需要一个 Controller script.php,您将从中禁用 Web 请求。您可以执行以下操作:
<?php
class script extends CI_Controller {
public function __construct() {
if(php_sapi_name() !== 'cli') {
show_404();
}
parent::__construct();
}
public function resizeImage($arg1, $arg2) {
//Whatever logic to resize image, or library call to do so.
}
}
3- 最后一部分是让您在 CI 中(在您的 system/application/libraries 文件夹中)开发一个包装器库,它将有效地包装 CloudController 的 worker 调用的功能
public function _construct() {
$ci = get_instance();
//add check to make sure that the value is set in the configuration
//Ideally since this is a library, pass the app_name in a setter to avoid creating a dependancy on the config object.
//Somewhere in one of your config files add $config['app_name'] = 'YOUR_APP_NAME/YOUR_DEP_NAME';
//where APP_NAME and DEP_NAME are cloud controller's app_name and dep_name
$this->_app_name = $ci->config->item('app_name');
//Also add: $config['utilities_script'] = 'path/to/utilities.php';
//This is the script created in step 1
$this->_utilities_script = $ci->config->item('utilities_script');
}
public function run() {
$args = func_get_args();
if(count($args) < 1 ) {
//We expect at least one arg which would be the command name
trigger_error('Run expects at least one argument', E_USER_ERROR);
}
$method = array_shift($args);
//utilities.php is the file created in step 1
$command = "cctrlapp " . $this->_app_name . " worker.add ".$this->_utilities_script;
//Add arguments if any
$command .= ' "'.implode(' ', $args).'"';
//finally...
exec($command);
}
}
4- 现在,如果来自 Controller ,则从代码中您实际想要排队作业的任何地方:
$this->load->library('Worker');
//resizeImage will call the method resizeImage in the script controller.
$this->worker->run('resizeImage', $width, $height);