CentOS5.2下Memcache的安裝與配置

餘二五發表於2017-11-15

 一,memcache簡單介紹:

memcached是高效能的分散式記憶體快取伺服器,為了提高效能,memcached中的資料都儲存在記憶體中,重啟memcached及重啟作業系統都會導致快取中的資料全部丟失,其快取的資料達到指定的記憶體分配值之後,就會使用LRU演算法刪除不使用的快取。(LRU演算法的基本概念:當分配的記憶體可用空間不足時,它儘可能地先保留最常用的資料,將最近沒有使用的資料移出記憶體,釋放出的空間來儲存其它的資料。)

其作用是快取資料庫查詢結果,這樣就減少了對資料庫的訪問次資料,從而減輕資料庫的壓力,這樣就提高了使用者的訪問速度,典型應用如下圖所示:

 

 

 

二,安裝伺服器端:

1,安裝libevent庫,它將Linuxepollfreebsd作業系統的kqueue等事件處理功能封裝成統一的介面,memcached使用這個庫,可以發揮其高效能。

[root@youxia205 opt]# yum install libevent libevent-devel

 

 

2,下載memcache原始碼包:

[root@youxia205 opt]# wget http://memcached.googlecode.com/files/memcached-1.4.5.tar.gz

 

 

3,解壓、編譯、安裝:

[root@youxia205 opt]# tar -zxvf memcached-1.4.5.tar.gz

[root@youxia205 opt]# cd memcached-1.4.5

[root@youxia205 memcached-1.4.5]# ./configure

[root@youxia205 memcached-1.4.5]# make && make install

 

 

4,安裝完成之後可以看下memcache的引數:

[root@youxia205 local]# memcached -help

memcached 1.4.5

-p <num>      TCP port number to listen on (default: 11211)

-U <num>      UDP port number to listen on (default: 11211, 0 is off)

-s <file>     UNIX socket path to listen on (disables network support)

-a <mask>     access mask for UNIX socket, in octal (default: 0700)

-l <ip_addr>  interface to listen on (default: INADDR_ANY, all addresses)

-d            run as a daemon

-r            maximize core file limit

-u <username> assume identity of <username> (only when run as root)

-m <num>      max memory to use for items in megabytes (default: 64 MB)

-M            return error on memory exhausted (rather than removing items)

-c <num>      max simultaneous connections (default: 1024)

-k            lock down all paged memory.  Note that there is a

              limit on how much memory you may lock.  Trying to

              allocate more than that would fail, so be sure you

              set the limit correctly for the user you started

              the daemon with (not for -u <username> user;

              under sh this is done with `ulimit -S -l NUM_KB`).

-v            verbose (print errors/warnings while in event loop)

-vv           very verbose (also print client commands/reponses)

-vvv          extremely verbose (also print internal state transitions)

-h            print this help and exit

-i            print memcached and libevent license

-P <file>     save PID in <file>, only used with -d option

-f <factor>   chunk size growth factor (default: 1.25)

-n <bytes>    minimum space allocated for key+value+flags (default: 48)

-L            Try to use large memory pages (if available). Increasing

              the memory page size could reduce the number of TLB misses

              and improve the performance. In order to get large pages

              from the OS, memcached will allocate the total item-cache

              in one large chunk.

-D <char>     Use <char> as the delimiter between key prefixes and IDs.

              This is used for per-prefix stats reporting. The default is

              “:” (colon). If this option is specified, stats collection

              is turned on automatically; if not, then it may be turned on

              by sending the “stats detail on” command to the server.

-t <num>      number of threads to use (default: 4)

-R            Maximum number of requests per event, limits the number of

              requests process for a given connection to prevent

              starvation (default: 20)

-C            Disable use of CAS

-b            Set the backlog queue limit (default: 1024)

-B            Binding protocol – one of ascii, binary, or auto (default)

-I            Override the size of each slab page. Adjusts max item size

              (default: 1mb, min: 1k, max: 128m)

 

5,啟動memcached服務:

[root@youxia205 local]# /usr/local/bin/memcached -u root -p 11211 -m 2048m -d

#-u是指執行memcache的使用者,-p是設定memcache監聽的埠,-m是分配給memcache使用的記憶體資料量

 -d是指作為daemon在後臺啟動。

 

 

6,檢視是否啟動成功:

[root@youxia205 local]# netstat -tunlp | grep memcache

tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN      14494/memcached    

udp        0      0 0.0.0.0:11211               0.0.0.0:*                               14494/memcached 

 

 

 

7,設定資料庫的相關資訊:

#建立一個名稱為mydb的庫:

mysql> create database mydb;

Query OK, 1 row affected (0.00 sec)

 

#使用庫,並建立personal_info表:

mysql> use mydb;

Database changed

mysql> CREATE TABLE `personal_info` (

    -> `pi_id` bigint(20) NOT NULL auto_increment,

    -> `pi_name` varchar(50) NOT NULL,

    -> `pi_tel` varchar(15) default NULL,

    -> `pi_qq` varchar(15) default NULL,

    -> `pi_email` varchar(50) default NULL,

    -> PRIMARY KEY (`pi_id`)

    -> ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

Query OK, 0 rows affected (0.00 sec)

 

#插入一條資料

mysql> INSERT INTO `mydb`.`personal_info` (

    -> `pi_id` ,

    -> `pi_name` ,

    -> `pi_tel` ,

    -> `pi_qq` ,

    -> `pi_email`

    -> )

    -> VALUES (

    -> `1`, `eric`, `13611031222`, `55555555`, `eric@nginxs.com`

    -> );

Query OK, 1 row affected (0.00 sec)

 

#檢視錶中的資料:

mysql> select * from  personal_info ;

+——-+———+————-+———-+—————–+

| pi_id | pi_name | pi_tel      | pi_qq    | pi_email        |

+——-+———+————-+———-+—————–+

|     1 | eric    | 13611031222 | 55555555 | eric@nginxs.com |

+——-+———+————-+———-+—————–+

1 row in set (0.00 sec)

 

 

 

 

三,安裝客戶端(需要PHP環境及PHPmemcache擴充套件):

1,由於伺服器已經安裝了ApacheMySQL,直接發安裝PHP,下載原始碼包:

[root@youxia205 opt]# wget http://www.php.net/get/php-5.2.14.tar.bz2/from/cn.php.net/mirror

 

2,解壓、編譯、安裝、配置:

[root@youxia205 opt]# tar -jxvf php-5.2.14.tar.bz2

[root@youxia205 opt]# cd php-5.2.14

 

[root@youxia205 php-5.2.14]# ./configure –prefix=/usr/local/php –with-apxs2=/usr/local/apache2/bin/apxs –with-config-file-path=/usr/local/php/etc –with-mysql=/var/lib/mysql –with-jpeg-dir

> –with-png-dir –with-bz2 –with-freetype-dir –with-iconv-dir  –enable-thread-safe-client

 

 

注:編譯PHP的時候遇到的錯誤:

configure: error: Cannot find libmysqlclient_r under /usr.

Note that the MySQL client library is not bundled anymore!

 

解決辦法如下:

[root@youxia205 php-5.2.14]# cp -r /usr/lib64/mysql/* /usr/lib/

 

[root@youxia205 php-5.2.14]# make && make install

 

[root@youxia205 php-5.2.14]# cp php.ini-dist /usr/local/php/etc/php.ini

 

[root@youxia205 ~]# vi /usr/local/apache2/conf/httpd.conf

 

在AddType application/x-gzip .gz .tgz下面新增

AddType application/x-httpd-php .php

 

在index.html後面新增index.php,如下所示:

<IfModule dir_module>

    DirectoryIndex index.html index.php

</IfModule>

 

 

3,啟動Apache服務:

[root@youxia205 htdocs]# /usr/local/apache2/bin/apachectl start

 

 

4,安裝memcachePHP擴充套件(下載原始碼包、編譯、安裝、配置):

[root@youxia205 opt]# wget http://pecl.php.net/get/memcache-2.2.5.tgz

 

[root@youxia205 opt]# tar -zxvf memcache-2.2.5.tgz

[root@youxia205 opt]# cd memcache-2.2.5

[root@youxia205 memcache-2.2.5]# /usr/local/php/bin/phpize

Configuring for:

PHP Api Version:         20041225

Zend Module Api No:      20060613

Zend Extension Api No:   220060519

 

[root@youxia205 memcache-2.2.5]# ./configure –enable-memcache -with-php-config=/usr/local/php/bin/php-config –with-zlib-dir

[root@youxia205 memcache-2.2.5]# make

[root@youxia205 memcache-2.2.5]# make install

Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-zts-20060613/

 

[root@youxia205 memcache-2.2.5]# vi /usr/local/php/etc/php.ini

extension=memcache.so

 

 

四,測試memcache

1,在網站目錄下建立一個測試檔案,名稱為memtest.php,具體如下:

[root@youxia205 ~]# cd  /usr/local/apache2/htdocs

[root@youxia205 htdocs]# vi memtest.php

<?php

$memcachehost = `192.168.0.205`;

$memcacheport = 11211;

$memcachelife = 60;

$memcache = new Memcache;

$memcache->connect($memcachehost,$memcacheport) or die (“Could not connect”);

$query=”select * from personal_info limit 10″;

$key=md5($query);

if(!$memcache->get($key))

{

                $conn=mysql_connect(“localhost”,”root“,”user);

                mysql_select_db(mydb);

                $result=mysql_query($query);

                while ($row=mysql_fetch_assoc($result))

                {

                        $arr[]=$row;

                }

                $f = `mysql`;

                $memcache->add($key,serialize($arr),0,30);        //mysql 查詢後,插入 memcached

                $data = $arr ;

}

else{

        $f = `memcache`;

        $data_mem=$memcache->get($key);

        $data = unserialize($data_mem);

}

echo $f;

echo “<br>”;

//print_r($data);

foreach($data as $a)

{

                echo “number is <b><font color=#FF0000>$a[pi_id]</font></b>”;

                echo “<br>”;

                echo “name is <b><font color=#FF0000>$a[pi_name]</font></b>”;

                echo “<br>”;

                echo “tel is <b><font color=#FF0000>$a[pi_tel]</font></b>”;

                echo “<br>”;

                echo “qq is <b><font color=#FF0000>$a[pi_qq]</font></b>”;

                echo “<br>”;

                echo “email is <b><font color=#FF0000>$a[pi_email]</font></b>”;

                echo “<br>”;

 

}

?>

 

2,執行測試:

#執行的時候報錯

Fatal error: Class `Memcache` not found in /usr/local/apache2/htdocs/memtest.php on line 5

 

#解決方法如下:

[root@youxia205 htdocs]# find / -name memcache.so

/usr/local/php/lib/php/extensions/no-debug-zts-20060613/memcache.so

/opt/memcache-2.2.5/.libs/memcache.so

/opt/memcache-2.2.5/modules/memcache.so

 

vi /usr/local/php/etc/php.ini

extension_dir = “./”

extension_dir = “/usr/local/php/lib/php/extensions/no-debug-zts-20060613”

 

 

再次執行:

 

 

 

檢視資料庫中正在執行的語句,沒有發現對mydb庫執行查詢的執行緒,說明PHP直接從memcache中提取的資料:

mysql> show processlist;

+—–+———-+—————–+——-+———+——+——-+——————+

| Id  | User     | Host            | db    | Command | Time | State | Info             |

+—–+———-+—————–+——-+———+——+——-+——————+

| 697 | prog     | localhost:44175      | word | Sleep   |   23 |       | NULL             |

| 698 | prog     | localhost:44176       | word | Sleep   |   23 |       | NULL             |

| 744 | user   | localhost              | mydb  | Sleep   | 3443 |       | NULL             |

| 747 | user   | localhost              | NULL  | Query   |    0 | NULL  | show processlist |

+—–+———-+—————–+——-+———+——+——-+——————+

4 rows in set (0.00 sec)

 

本文轉自 trt2008 51CTO部落格,原文連結:http://blog.51cto.com/chlotte/383327,如需轉載請自行聯絡原作者


相關文章