memcache用內存緩存技術來實現對訪問php頁面的加速

一、什麼是Memcache

Memcache是一個自由、源碼開放、高性能、分佈式的分佈式內存對象緩存系統,用於動態Web應用用來減輕數據庫的負載。它通過在內存中緩存數據和對象來減少讀取數據庫的次數,從而提高了網站訪問的速度

二、Memcache的應用場景

通常情況下,我們會在訪問量較高的Web網站和應用中使用Memcache,用來環節數據庫的壓力,並且提升網站和應用的響應速度
在應用程序中,我們通常在以下節點來使用Memcached:

  1. 訪問頻繁的數據庫數據(身份token、首頁動態)
  2. 訪問頻繁的查詢條件和結果
  3. 作爲session的存儲方式(提高session存取性能)
  4. 頁面緩存
  5. 更新頻繁的非重要數據(訪客量、點擊次數)
  6. 大量的hot數據
    ** 常用的工作流程**:先檢查客戶端的請求數據是否在memcached中,如果有的話,直接把請求數據返回,不再對數據庫進行任何操作;如果請求的數據不在memcache中,就去查數據庫,把從數據庫中獲取的數據返回個客戶端,同時把數據緩存一份到memcached中;每次更新數據庫的同時更新memcached中的數據,保證一致性;當分配個memcached內存空間用完之後會使用LRU(least recently used,最近最少使用)策略加上到期失效策略,失效數據首先被替換,然後再替換掉最近未使用的數據
    在這裏插入圖片描述

三、Memcache的服務器端和客戶端的安裝

1、創建一個預編譯環境並進行編譯彙編memcache源碼包

phpize是用來擴展php擴展模塊的,通過phpize可以建立php的外掛模塊,比如你想在原來編譯好的php中加入memcached模塊或是ImageMagick等模塊,可以使用phpize
在這裏插入圖片描述

2、如何使用phpize

當php編譯完成之後,會在php的bin目錄下生成一個phpize這個腳本文件,
現在想在php中加入memcache擴展模塊

[root@server1 ~]# tar zxf memcache-2.2.5.tgz
  • 將前面php編譯完成的二進制命令加入到系統的環境變量中,保證可以直接調用php命令
[root@server1 bin]# vim ~/.bash_profile 
[root@server1 bin]# source ~/.bash_profile 
  • 將在php中擴展memcache模塊
[root@server1 ~]# cd /usr/local/lnmp/php/etc/
[root@server1 etc]# vim php.ini
 873   extension=memcache.so
 [root@server1 etc]# /etc/init.d/php-fpm reload
Reload service php-fpm  done
  • 設置memcached密碼
[root@server1 ~]# cd memcache-2.2.5
[root@server1 memcache-2.2.5]# cp example.php memcache.php /usr/local/lnmp/nginx/html/
[root@server1 memcache-2.2.5]# cd /usr/local/lnmp/nginx/html/
[root@server1 html]# vim memcache.php

在這裏插入圖片描述

  • 安裝memcache服務端
[root@server1 html]# yum install -y memcached
[root@server1 html]# /etc/init.d/memcached start

訪問example.php
在這裏插入圖片描述
訪問memecache.php
在這裏插入圖片描述
登錄進去之後:刷新example.php頁面,可以在下圖中看到hit命中率,刷新的次數越多,命中率越高,當多次訪問,命中率可達到百分之百
在這裏插入圖片描述

  • **訪問測試
    ab(apache bench)是apache下的一個工具,主要用於對web站點做壓力測試
    在主機中測試
[root@foundation66 kiosk]# ab -c 10 -n 1000 http://172.25.66.1/index.php

在這裏插入圖片描述

[root@foundation66 kiosk]# ab -c 10 -n 1000 http://172.25.66.1/example.php

在這裏插入圖片描述
當訪問example.php時,命中率大大提高,速度也提高了將近三倍。
註解:ab -c 10 -n 1000 http://172.25.66.1/example.php 測試結果分析

Server Software:        nginx/
Server Hostname:        172.25.66.1
Server Port:            80

Document Path:          /index.php
Document Length:        123 bytes	#請求的頁面大小

Concurrency Level:      10		#併發量
Time taken for tests:   0.656 seconds		#測試總共耗時
Complete requests:      1000	#完成的請求
Failed requests:         	0		#失敗的請求
   (Connect: 0, Receive: 0, Length: 909, Exceptions: 0)
Write errors:           0		#錯誤
Total transferred:      280000 bytes		#總共傳輸數據量
HTML transferred:      123000  bytes
Requests per second:     1525.84 [#/sec] (mean)	#每秒鐘的請求量
Time per request:       6.554  [ms] (mean)			#平均請求等待時間(用戶等待時間)
Time per request:      0.655  [ms] (mean, across all concurrent requests)	#服務器平均請求響應時間,在併發量爲1時,用戶等待時間相同
Transfer rate:         417.22  [Kbytes/sec] received		#平均每秒多少k,即就是帶寬速率
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章