강좌게시판

제목 queue 배치 작업
글쓴이 작성시각 2015/10/20 10:04:49
댓글 : 1 추천 : 0 스크랩 : 1 조회수 : 22460   RSS
 안녕하세요.
선배님들 강좌를 보다가 제 시스템에 적용하려니 환경이 맞지 않더라고요.
저와 같이 몇날몇일 고생하실 분을 위해 미흡하지만 몇자 적어봤습니다.
http://www.cikorea.net/lecture/view/298/page/1 <<< [상급] CodeIgniter + MQ, Parallel Processing 강좌
제환경은 mariadb + nginx + php + linux (centos7) 입니다.
강좌를 읽다보니 강좌 자체가 몽고 디비를 바탕으로 되어있더라고요.
그래서 별도로 설치하는걸 힘들어 하는 저는 mysql이나 mariadb는 안되는건가 해서 찾기 시작했습니다.
찾다보니 https://opentutorials.org/module/327/4130 <<< Queue & Cron 이란 강좌가 있더라고요.
아 충분히 가능하겠구나 라는 판단을 한 저는 약간의 두려움을 갖고 작업을 시작했습니다.

config 설정입니다. (웅파님이 알려주신 소스로 잘 이용중이었는데 오류가 나서 cli모드일경우 경로를 분기하는....)

//cli모드가 아니면..
if(php_sapi_name() != 'cli'){
    $config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
    $config['base_url'] .= "://" . $_SERVER['HTTP_HOST'];
    $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
}else{
    $config['base_url'] = "경로";
}

cron 설정입니다. (리눅스 스케쥴러로 crontab -e로 편집합니다.)
#자동업데이트 큐에 *****(작업)를 넣는다.
35 8,11,14,17,20,23 * * * su - root -c '/(경로)/php -q /(경로)/index.php 컨트롤러 queue_add(메소드) 인자'

큐로 등록할 테이블

CREATE TABLE `테이블명` (
  `aq_no` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `aq_job_name` varchar(50) NOT NULL,
  PRIMARY KEY (`aq_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


컨트롤러 입니다.


class 컨트롤러 extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('모델명');
	}
	
	public function index(){
		
	}
	
	public function queue_add ($job_name="") {
		if($job_name == ""){
			echo "잡이 정의되지 않음."; 
			exit;
		}
		$this->모델명->queue_add($job_name);
	}
	
	
	public function start_queue () {
		while (1) {
			$result = $this->모델명->get_queue();
			$cur_count = $result->num_rows();
			if ($cur_count > 0) {
				// 작업이 있으면 일을 시작해라.
				$this->모델명->process_queue($result);
			} else {
				// 없으면 잠시 기달림.
				sleep(rand(3, 7));
			}
		}
	}
}

모델입니다.
line = "\n";
        if(php_sapi_name() != 'cli') $this->line = "
";
    }
        
    //큐데이터 객체 리턴
    function get_queue() {
    	
    	$this->db->select("*");
    	$this->db->from("테이블명");
    	$this->db->order_by("aq_no","asc");
    	$query = $this->db->get();
    	
    	return $query;
    }
    
    //큐 실행.
    function process_queue($obj) {
    	$row = $obj->row_array();
    	
    	//큐삭제..
    	$this->db->delete('테이블명', array('aq_no' => $row['aq_no']));
    	
    	if(method_exists( $this,$row['aq_job_name'] )){
    		//예외가 발생할 수 있으니 큐 삭제 후 실행.
    		$this->$row['aq_job_name']();
    	}
    }
    
    //큐추가
    function queue_add($job_name) {
    	
    	$this->db->select("*");
    	$this->db->from("테이블명");
    	$this->db->where("aq_job_name",$job_name);
    	$this->db->order_by("aq_no","asc");
    	$query = $this->db->get();
    	//중복 등록을 막으려고 넣었어요  필요없으시면 빼도됨.
    	if( $query->num_rows() > 0 ){
	    	return false; 
    	} else {
    		$sql = array(
    				'aq_job_name'	=>	$job_name
    		);
    		$result = $this->db->insert('테이블명', $sql);
    		
    		return true;
    	}
    }
    
    function __destruct () {
    	
    }
}


supervisord.conf  설정입니다.
[program:mysite]
command = php /경로/index.php 컨트롤러 start_queue
process_name=%(program_name)s_mysite%(process_num)02d
numprocs=1 // 프로세스 수
autorestart=true
autostart=true

작업전엔 두려움이 컸는데 생각한 대로 실행되니 너무 기뻤습니다.
필요에 맞게 수정해서 사용하시면 될거 같습니다.


 
 다음글 서브 디렉토리 index.php 죽이기 (5)
 이전글 [게임서버] 구글영수증 검증 (강좌마감) (5)

댓글

한대승(불의회상) / 2015/10/20 10:57:56 / 추천 0
큐서버를 구축 하기 힘들경우 아주 유용 할 것 같습니다.
좋은 강의 감사 합니다.