웹사이트 검색

Ubuntu 12.04에서 Memcache를 설치하고 사용하는 방법


상태: 더 이상 사용되지 않음

이 문서에서는 더 이상 지원되지 않는 Ubuntu 버전에 대해 설명합니다. 현재 Ubuntu 12.04를 실행하는 서버를 운영 중인 경우 지원되는 Ubuntu 버전으로 업그레이드하거나 마이그레이션하는 것이 좋습니다.

  • Ubuntu 14.04로 업그레이드합니다.
  • Ubuntu 14.04에서 Ubuntu 16.04로 업그레이드
  • 서버 데이터를 지원되는 버전으로 마이그레이션

이유:

대신 참조:

Memcache 정보

Memcache는 서버 정보를 캐싱하여 가상 사설 서버의 속도를 높이는 시스템입니다. 이 프로그램을 사용하면 일정 시간 동안 최근에 쿼리한 데이터를 캐싱하기 위해 특정 양의 서버 램을 할당할 수 있습니다. 데이터가 다시 요청되면 Memcache는 데이터베이스에서 결과를 생성하는 대신 캐시된 정보를 표시하여 검색 프로세스 속도를 높입니다.

설정

이 자습서의 단계를 수행하려면 사용자에게 루트 권한이 있어야 합니다. 기본 사용자 자습서에서 설정 방법을 확인할 수 있습니다.

sudo apt-get update

또한 가상 서버에 MySQL 및 PHP가 설치되어 있어야 합니다.

sudo apt-get install mysql-server php5-mysql php5 php5-memcache

Memcache 설치

Memcache를 설치하려면 여러 단계를 거쳐야 합니다.

시작하려면 apt-get을 통해 memcached를 설치합니다.

sudo apt-get install memcached

다음 단계는 memcache를 저장하는 저장소인 php-pear를 설치하는 것입니다.

sudo apt-get install php-pear

서버에 컴파일러가 없는 경우 memcache를 설치하기 위해 build-essential을 다운로드할 수 있습니다.

sudo apt-get install build-essential

마지막으로 PECL(PHP Extension Community Library)을 사용하여 memcache를 설치합니다.

sudo pecl install memcache

설치 중에 "Enable memcache session handler support? [yes] :”를 묻는 메시지가 표시되면 Enter 키를 눌러 예라고 말하십시오.

VPS에서 PECL로 memcache 설치를 완료했으면 memcache.ini에 memcached를 추가합니다.

echo "extension=memcache.so" | sudo tee /etc/php5/conf.d/memcache.ini

이제 Memcache를 사용할 준비가 되었습니다.

Memcache 확인 및 통계 보기

Memcache를 다운로드한 후 검색하여 설치되었는지 확인할 수 있습니다.

ps aux | grep memcache

또한 다음을 입력하여 Memcache 통계를 볼 수 있습니다.

echo "stats settings" | nc localhost 11211

3단계 - Memcache 작동 방식

Memcache는 서버의 데이터베이스를 쿼리하기 전에 먼저 캐시에서 데이터 검색을 시도하도록 코드를 리디렉션하는 방식으로 작동합니다. 캐시는 최근에 검색된 서버 데이터를 일정 시간 동안 저장하여 채웁니다. 최근에 요청한 정보를 캐시하면 향후 쿼리는 데이터베이스에서 정보를 검색하는 더 긴 프로세스를 거칠 필요가 없으며 대신 캐시를 통해 정보에 액세스할 수 있습니다.

Memcache 페이지는 Memcache 프로세스를 요약하기 위해 홈페이지에 이 축약된 코드를 표시합니다.

function get_foo(foo_id)
    foo = memcached_get("foo:" . foo_id)
    return foo if defined foo

    foo = fetch_foo_from_database(foo_id)
    memcached_set("foo:" . foo_id, foo)
    return foo
end

간단한 Memcache 예

이 섹션에서는 원래 mysql 테이블에서 찾은 단일 값을 검색하기 위해 memcache를 사용하는 간단한 php 스크립트를 설정합니다.

다음 단계에서는 적절한 데이터베이스에 액세스할 수 있는 mysql 사용자를 설정하고, 쿼리할 테이블을 만들고, 새 mysql 테이블에서 테스트할 하나의 값을 삽입합니다.

mysql에 로그인: mysql -u root -p 다음 명령을 실행합니다.

use test;

grant all on test.* to test@localhost identified by 'testing123';

create table example (id int, name varchar(30));

insert into example values (1, "new_data");

exit;

MySQL을 종료한 후 memcache 스크립트 파일을 생성합니다.

nano memtest.php

이제 php 스크립트를 단계별로 구축할 것입니다(전체 스크립트는 섹션의 끝에 있습니다).

  • Start off by creating a new persistent connection with memcache, which runs on memcache’s default port, 11211.
    <?php
    $meminstance = new Memcache();
    $meminstance->pconnect('localhost', 11211);
  • The next step is to connect to the new mysql database with the user that we created earlier:
    mysql_connect("localhost", "test", "testing123") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());
  • After that, go ahead and create the query that we will pose to the server, as well as provide a key to identify that specific action:
    $query = "select id from example where name = 'new_data'";
    $querykey = "KEY" . md5($query);
  • The script first searches the cache for the answer to the query. If the result does not exist, the script reroutes the question to the original database. Once the query has been answered by the original database, the script stores the result in memcache, using the “set” command-- which both saves it and allows the user to designate the number of seconds that it should remain in the cache (600 would save it in the cache for 10 minutes).

    When we run the script for the first time, it will inform us that the data was collected from the mysql database. However, as it does so, it stores the information in the cache, so that a second run of the script retrieves it from the cache and lets the user know.

    In 10 minutes the cache is emptied once more and running the script will make it access the database once again.

    $result = $meminstance->get($querykey);
    
    if (!$result) {
           $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
           $meminstance->set($querykey, $result, 0, 600);
    print "got result from mysql\n";
    return 0;
    }
    
    print "got result from memcached\n";
    return 0;
    
    ?>

전체적으로 스크립트는 다음과 같습니다.

<?php
$meminstance = new Memcache();
$meminstance->pconnect('localhost', 11211);

mysql_connect("localhost", "test", "testing123") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());

$query = "select id from example where name = 'new_data'";
$querykey = "KEY" . md5($query);

$result = $meminstance->get($querykey);

if (!$result) {
       $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
       $meminstance->set($querykey, $result, 0, 600);
print "got result from mysql\n";
return 0;
}

print "got result from memcached\n";
return 0;

?>

명령줄에서 스크립트를 실행하면 다음 결과가 생성됩니다.

# php memtest.php 
got result from mysql

# php memtest.php 
got result from memcached

# php memtest.php 
got result from memcached

결론

이 튜토리얼에서는 데이터베이스를 memcache에 연결하여 데이터베이스에서 데이터 검색 속도를 높이는 방법을 다룹니다. 그러나 Memcache의 장점은 데이터 저장소가 아닌 캐시라는 사실에 있습니다. memcache를 사용할 때 데이터베이스를 대체할 것이라고 기대하지 마십시오. Memcache는 지정된 키에 대해 설정된 시간 동안만 값을 보유하기 때문에 캐시에 필요한 정보를 항상 찾지 못할 수 있으며, 이러한 경우 원래 서버 데이터베이스를 보유하는 것이 필수적입니다.

그럼에도 불구하고 memcache는 매우 유용한 프로그램이며 서버 효율성을 높이기 위해 많은 일을 할 수 있습니다.

Memcache에 대해 다른 질문이 있는 경우 포럼에서 세부 사항에 대해 질문하십시오.