国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
PHP如何使用Memcached,PHP使用Memcached
您可能感興趣的文章:
Home php教程 php手冊(cè) PHP如何使用Memcached,PHP使用Memcached

PHP如何使用Memcached,PHP使用Memcached

Jun 13, 2016 am 08:42 AM
memcached php

PHP如何使用Memcached,PHP使用Memcached

一、memcached 簡(jiǎn)介

memcached是高性能的分布式內(nèi)存緩存服務(wù)器。一般的使用目的是,通過(guò)緩存數(shù)據(jù)庫(kù)查詢結(jié)果,減少數(shù)據(jù)庫(kù)訪問(wèn)次數(shù),以提高動(dòng)態(tài)Web應(yīng)用的速度、提高可擴(kuò)展性。它可以應(yīng)對(duì)任意多個(gè)連接,使用非阻塞的網(wǎng)絡(luò)IO。由于它的工作機(jī)制是在內(nèi)存中開(kāi)辟一塊空間,然后建立一個(gè)HashTable,Memcached自管理這些HashTable。

二、memcached 安裝

首先是下載 memcached 了,目前最新版本是 1.1.12,直接從官方網(wǎng)站即可下載到 memcached-1.1.12.tar.gz。除此之外,memcached 用到了 libevent,我下載的是 libevent-1.1a.tar.gz。

接下來(lái)是分別將 libevent-1.1a.tar.gz 和 memcached-1.1.12.tar.gz 解開(kāi)包、編譯、安裝:
# tar -xzf libevent-1.1a.tar.gz # cd libevent-1.1a# ./configure --prefix=/usr# make# make install# cd .. # tar -xzf memcached-1.1.12.tar.gz# cd memcached-1.1.12 # ./configure --prefix=/usr# make# make install
安裝完成之后,memcached 應(yīng)該在 /usr/bin/memcached。

三、運(yùn)行 memcached 守護(hù)程序

運(yùn)行 memcached 守護(hù)程序很簡(jiǎn)單,只需一個(gè)命令行即可,不需要修改任何配置文件(也沒(méi)有配置文件給你修改 ):
/usr/bin/memcached -d -m 128 -l 192.168.1.1 -p 11211 -u httpd
參數(shù)解釋:

-d 以守護(hù)程序(daemon)方式運(yùn)行 memcached;-m 設(shè)置 memcached 可以使用的內(nèi)存大小,單位為 M; -l 設(shè)置監(jiān)聽(tīng)的 IP 地址,如果是本機(jī)的話,通??梢圆辉O(shè)置此參數(shù);-p 設(shè)置監(jiān)聽(tīng)的端口,默認(rèn)為 11211,所以也可以不設(shè)置此參數(shù); -u 指定用戶,如果當(dāng)前為 root 的話,需要使用此參數(shù)指定用戶。

當(dāng)然,還有其它參數(shù)可以用,man memcached 一下就可以看到了。

四、memcached 的工作原理

首先 memcached 是以守護(hù)程序方式運(yùn)行于一個(gè)或多個(gè)服務(wù)器中,隨時(shí)接受客戶端的連接操作,客戶端可以由各種語(yǔ)言編寫,目前已知的客戶端 API 包括 Perl/PHP/Python/Ruby/Java/C#/C 等等。PHP 等客戶端在與 memcached 服務(wù)建立連接之后,接下來(lái)的事情就是存取對(duì)象了,每個(gè)被存取的對(duì)象都有一個(gè)唯一的標(biāo)識(shí)符 key,存取操作均通過(guò)這個(gè) key 進(jìn)行,保存到 memcached 中的對(duì)象實(shí)際上是放置內(nèi)存中的,并不是保存在 cache 文件中的,這也是為什么 memcached 能夠如此高效快速的原因。注意,這些對(duì)象并不是持久的,服務(wù)停止之后,里邊的數(shù)據(jù)就會(huì)丟失。

五、PHP 如何作為 memcached 客戶端

有兩種方法可以使 PHP 作為 memcached 客戶端,調(diào)用 memcached 的服務(wù)進(jìn)行對(duì)象存取操作。

第一種,PHP 有一個(gè)叫做 memcache 的擴(kuò)展,Linux 下編譯時(shí)需要帶上 –enable-memcache[=DIR] 選項(xiàng),Window 下則在 php.ini 中去掉 php_memcache.dll 前邊的注釋符,使其可用。

除此之外,還有一種方法,可以避開(kāi)擴(kuò)展、重新編譯所帶來(lái)的麻煩,那就是直接使用 php-memcached-client。

本文選用第二種方式,雖然效率會(huì)比擴(kuò)展庫(kù)稍差一些,但問(wèn)題不大。

六、PHP memcached 應(yīng)用示例

首先 下載 memcached-client.php,在下載了 memcached-client.php 之后,就可以通過(guò)這個(gè)文件中的類“memcached”對(duì) memcached 服務(wù)進(jìn)行操作了。其實(shí)代碼調(diào)用非常簡(jiǎn)單,主要會(huì)用到的方法有 add()、get()、replace() 和 delete(),方法說(shuō)明如下:

復(fù)制代碼 代碼如下:
add ($key, $val, $exp = 0)

往 memcached 中寫入對(duì)象,$key 是對(duì)象的唯一標(biāo)識(shí)符,$val 是寫入的對(duì)象數(shù)據(jù),$exp 為過(guò)期時(shí)間,單位為秒,默認(rèn)為不限時(shí)間;

get ($key)

從 memcached 中獲取對(duì)象數(shù)據(jù),通過(guò)對(duì)象的唯一標(biāo)識(shí)符 $key 獲取;

復(fù)制代碼 代碼如下:
replace ($key, $value, $exp=0)

使用 $value 替換 memcached 中標(biāo)識(shí)符為 $key 的對(duì)象內(nèi)容,參數(shù)與 add() 方法一樣,只有 $key 對(duì)象存在的情況下才會(huì)起作用;

復(fù)制代碼 代碼如下:
delete ($key, $time = 0)

刪除 memcached 中標(biāo)識(shí)符為 $key 的對(duì)象,$time 為可選參數(shù),表示刪除之前需要等待多長(zhǎng)時(shí)間。

下面是一段簡(jiǎn)單的測(cè)試代碼,代碼中對(duì)標(biāo)識(shí)符為 'mykey' 的對(duì)象數(shù)據(jù)進(jìn)行存取操作:

<&#63;php
// 包含 memcached 類文件
require_once('memcached-client.php');
// 選項(xiàng)設(shè)置
$options = array(
'servers' => array('192.168.1.1:11211'), //memcached 服務(wù)的地址、端口,可用多個(gè)數(shù)組元素表示多個(gè) memcached 服務(wù)
'debug' => true, //是否打開(kāi) debug
'compress_threshold' => 10240, //超過(guò)多少字節(jié)的數(shù)據(jù)時(shí)進(jìn)行壓縮
'persistant' => false //是否使用持久連接
);
// 創(chuàng)建 memcached 對(duì)象實(shí)例
$mc = new memcached($options);
// 設(shè)置此腳本使用的唯一標(biāo)識(shí)符
$key = 'mykey';
// 往 memcached 中寫入對(duì)象
$mc->add($key, 'some random strings');
$val = $mc->get($key);
echo "n".str_pad('$mc->add() ', 60, '_')."n";
var_dump($val);
// 替換已寫入的對(duì)象數(shù)據(jù)值
$mc->replace($key, array('some'=>'haha', 'array'=>'xxx'));
$val = $mc->get($key);
echo "n".str_pad('$mc->replace() ', 60, '_')."n";
var_dump($val);
// 刪除 memcached 中的對(duì)象
$mc->delete($key);
$val = $mc->get($key);
echo "n".str_pad('$mc->delete() ', 60, '_')."n";
var_dump($val);
&#63;> 

是不是很簡(jiǎn)單,在實(shí)際應(yīng)用中,通常會(huì)把數(shù)據(jù)庫(kù)查詢的結(jié)果集保存到 memcached 中,下次訪問(wèn)時(shí)直接從 memcached 中獲取,而不再做數(shù)據(jù)庫(kù)查詢操作,這樣可以在很大程度上減輕數(shù)據(jù)庫(kù)的負(fù)擔(dān)。通常會(huì)將 SQL 語(yǔ)句 md5() 之后的值作為唯一標(biāo)識(shí)符 key。下邊是一個(gè)利用 memcached 來(lái)緩存數(shù)據(jù)庫(kù)查詢結(jié)果集的示例(此代碼片段緊接上邊的示例代碼):

<&#63;php
$sql = 'SELECT * FROM users';
$key = md5($sql); //memcached 對(duì)象標(biāo)識(shí)符
if ( !($datas = $mc->get($key)) ) {
// 在 memcached 中未獲取到緩存數(shù)據(jù),則使用數(shù)據(jù)庫(kù)查詢獲取記錄集。
echo "n".str_pad('Read datas from MySQL.', 60, '_')."n";
$conn = mysql_connect('localhost', 'test', 'test');
mysql_select_db('test');
$result = mysql_query($sql);
while ($row = mysql_fetch_object($result))
$datas[] = $row;
// 將數(shù)據(jù)庫(kù)中獲取到的結(jié)果集數(shù)據(jù)保存到 memcached 中,以供下次訪問(wèn)時(shí)使用。
$mc->add($key, $datas);
} else {
echo "n".str_pad('Read datas from memcached.', 60, '_')."n";
}
var_dump($datas);
&#63;> 

可以看出,使用 memcached 之后,可以減少數(shù)據(jù)庫(kù)連接、查詢操作,數(shù)據(jù)庫(kù)負(fù)載下來(lái)了,腳本的運(yùn)行速度也提高了。

之前我曾經(jīng)寫過(guò)一篇名為《PHP 實(shí)現(xiàn)多服務(wù)器共享 SESSION 數(shù)據(jù)》文章,文中的 SESSION 是使用數(shù)據(jù)庫(kù)保存的,在并發(fā)訪問(wèn)量大的時(shí)候,服務(wù)器的負(fù)載會(huì)很大,經(jīng)常會(huì)超出 MySQL 最大連接數(shù),利用 memcached,我們可以很好地解決這個(gè)問(wèn)題,工作原理如下:

用戶訪問(wèn)網(wǎng)頁(yè)時(shí),查看 memcached 中是否有當(dāng)前用戶的 SESSION 數(shù)據(jù),使用 session_id() 作為唯一標(biāo)識(shí)符;如果數(shù)據(jù)存在,則直接返回,如果不存在,再進(jìn)行數(shù)據(jù)庫(kù)連接,獲取 SESSION 數(shù)據(jù),并將此數(shù)據(jù)保存到 memcached 中,供下次使用; 當(dāng)前的 PHP 運(yùn)行結(jié)束(或使用了 session_write_close())時(shí),會(huì)調(diào)用 My_Sess::write() 方法,將數(shù)據(jù)寫入數(shù)據(jù)庫(kù),這樣的話,每次仍然會(huì)有數(shù)據(jù)庫(kù)操作,對(duì)于這個(gè)方法,也需要進(jìn)行優(yōu)化。使用一個(gè)全局變量,記錄用戶進(jìn)入頁(yè)面時(shí)的 SESSION 數(shù)據(jù),然后在 write() 方法內(nèi)比較此數(shù)據(jù)與想要寫入的 SESSION 數(shù)據(jù)是否相同,不同才進(jìn)行數(shù)據(jù)庫(kù)連接、寫入數(shù)據(jù)庫(kù),同時(shí)將 memcached 中對(duì)應(yīng)的對(duì)象刪除,如果相同的話,則表示 SESSION 數(shù)據(jù)未改變,那么就可以不做任何操作,直接返回了; 那么用戶 SESSION 過(guò)期時(shí)間怎么解決呢?記得 memcached 的 add() 方法有個(gè)過(guò)期時(shí)間參數(shù) $exp 嗎?把這個(gè)參數(shù)值設(shè)置成小于 SESSION 最大存活時(shí)間即可。另外別忘了給那些一直在線的用戶延續(xù) SESSION 時(shí)長(zhǎng),這個(gè)可以在 write() 方法中解決,通過(guò)判斷時(shí)間,符合條件則更新數(shù)據(jù)庫(kù)數(shù)據(jù)。

以上內(nèi)容是小編給大家介紹的PHP如何使用Memcached,希望對(duì)大家有所幫助!

您可能感興趣的文章:

  • PHP5.5在windows安裝使用memcached服務(wù)端的方法
  • PHP模塊memcached使用指南
  • PHP擴(kuò)展模塊memcached長(zhǎng)連接使用方法分析
  • PHP 使用memcached簡(jiǎn)單示例分享
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles