PHP 학습
공유메모리를 이용하여 순차적으로 값 추출하기
다수의 DB서버를 이용하여 connect할 경우 사용하면 유용합니다.
master 서버를 제외한 slave 서버중에서 한곳으로 connect를 하고자 할 경우
공유메모리를 이용하여 순차적으로 connect를 한다면 DB서버에 거의 균등하게 접속할 수 있습니다.
방식: A, B, C 세개의 DB서버가 있다고 간주합니다.
만약 내가 A서버에 접속하여 있다면 다음에 접속하는 사람은 B서버로, 그다음에 접속하는 사람은 C서버로 이런식으로 A->B->C 이런 순서로 접속이 이뤄지게 됩니다.
더불어 DB서버를 모니터링을 하여 어느 한쪽으로 치우치지 않는지 확인해봅니다.
제가 적용하여 테스트 했을 때는 아주 동일하지는 않지만 세개의 서버가 거의 유사하게 이용율을 보였습니다.
보다 자세한 사항은 첨부된 문서를 보시면 알수 있습니다.
<?
function memsegspot($str){
$str = str_pad($str, 4, "Z");
for ($a=0; $a<4; $a++) {
$out1 = substr($str, $a , 1);
$out .= dechex(ord($out1));
}
return ("0x".$out);
}
function ip($arr) {
# 공유 메모리 지정
$shmKey = 0x8888;
$semid = sem_get($shmKey, 10);
sem_acquire($semid);
$sheKey = memsegspot((serialize("suid")));
$shmid = shm_attach($shmKey);
# 공유메모리에 저장된 값 불러오기
$result = shm_get_var($shmid, $testing);
if(!$result) {
shm_remove_var($shmid, $testing);
# 공유메모리에 저장하기
shm_put_var ($shmid, $shm_variable,$arr[0]);
$result = shm_get_var($shmid, $testing);
} else {
shm_remove_var($shmid, $testing);
for($i=0;$i<sizeof($arr);$i++) {
echo "[SHM: $result / IP: $arr[$i]]<br>";
if($arr[$i] == $result) {
$check = $i + 1;
if ($check > (sizeof($arr) - 1)) $check = 0;
# 공유메모리에 저장하기
shm_put_var($shmid, $shm_variable, $arr[$check]);
}
}
$result = shm_get_var($shmid, $testing);
}
shm_detach($shmid);
sem_release($semid);
return $result;
}
$str_ipNum = array ("111.111.111.111","222.222.222.222","333.333.333.333"); // slave
$Host = ip($str_ipNum);
echo "SHM: [$Host]";
?>
※ 해당 소스로 인해 발생된 문제는 본인이 책임지지 않으며, 충분한 테스트후 적용하시길 바랍니다.

