PHP operations on memcache and phpmemcache

Source: Internet
Author: User
Tags pconnect unix domain socket

PHP operations on memcache and phpmemcache
* In the [1] Directory, install [2] connect to [3] add, delete, modify, and Query [4] distributed [5] status [6] Security [7] before the application

Similar to accessing the mysql server, PHP accesses the memcached server as a client API. Therefore, you also need to install the memcache extension interface for the PHP program. memcache and memcached extensions are commonly used. Memcached and memcache Daemon have the same name as memcached, which may be confusing. memcached is the backend daemon that some people think of first. It is necessary to analyze the differences between the two. Memcache is fully developed in the PHP framework, while memecached uses libmemcached. From the manual, memcached has several more methods than memcache, and the usage is similar. Memcache is implemented in native mode, but memached using libmemcached only supports OO interfaces, while memcache uses OO and non-OO interfaces. Later, with the improvement of memcached server, this lib will be followed up immediately. However, memcache may not be able to follow up on time. Memcached is also very praised, that is, the flag is not set during the operation. Instead, there is a unified setOption (). Memcached implements more memcached protocols (after all, it is based on the libmemcached library ). This article selects a simple memcache extension for introduction

 

Install

Installing memcache extension in the window system is relatively simple. Download a memcache extension library consistent with the PHP version.

Save the downloaded php_memcache.dll file to the PHP application extension ext directory.

Add the extension location to the php. ini file and add a line "extension = php_memcache.dll"

Restart the apache server. You can use phpInfo () to find that the memcache service has been installed.

 

Connection

Since the Memcache application interface of PHP is used as the client of the memcached server, you must first connect to the memcached server. The Memcache: connect () method is used to connect to a memcached server. If the connection is successful, true is returned. Otherwise, false is returned.

bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )

This method has three parameters. The first parameter host (required) indicates the address of the memcached server listening host. The second parameter port indicates the memcached server listening port (Optional). The default value is 11211; the third parameter timeout indicates the connection duration (timeout), in seconds. The default value is 1 second.

[Note] Too long connection duration may lead to loss of all cache advantages

Use Memcache: connect () to connect to the memcached server. After completing the operation, you can use the Memcache: close () method to close the connection and complete some session processes. To connect to the memcached server in persistent connection mode, you can use the Memcache: pconnect () method. The call method of this method is the same as that of Memcache: connect, however, persistent connections cannot be closed by the Memcache: close () method.

// Instantiate the object $ memcache = new Memcache; // connect to the memcache server $ memcache-> connect ('localhost '); /* Other Operations * // close the connection $ memcache-> close ();

 

Add, delete, modify, and query

Add

After successfully connecting to the memcached server, you can add a data (add) to be cached and complete it through Memcache: add ().

bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )

In the add () method, the parameter key indicates the key to be allocated to the variable; the parameter var indicates the variable to be stored. Strings and integer types are stored in the original text, and Other types are serialized and stored. The parameter flag (optional) indicates that the data is compressed using the MEMCACHE_COMPRESSED mark (using zlib); the parameter expire (optional) indicates the expiration time of the data currently written to the cache. If this value is set to 0, the Data never expires. You can set a UNIX timestamp or an integer in seconds (Time Difference calculated from the current time) to indicate the data expiration time. However, in the latter method, cannot exceed 2592000 seconds (30 days)

$memcache->add('id1','11111');

Delete

Memcache: delete ()

Memcache: delete-delete an element from the server

bool Memcache::delete ( string $key [, int $timeout = 0 ] )

The delete method has two parameters. The key parameter indicates the key of the element to be deleted, and the timeout parameter indicates the execution time of the element to be deleted. If the value is 0, the element is deleted immediately. If the value is 30, the element will be deleted within 30 seconds.

$memcache->delete('id1');

Memcache: flush

  Memcache: flush-clean (delete) all elements that have been stored. Returns TRUE if the call succeeds, or FALSE if the call fails.

bool Memcache::flush ( void )

[Note] Memcache: flush () immediately invalidates all existing elements. Method Memcache: flush () does not actually release any resources, but only indicates that all elements are invalid. Therefore, the memory used will be rewritten by new elements.

Modify

Memcache: set

Memcache: set-sets the cache content of a specified key.

bool Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] )

[Note] set () has an alias of replace ()

$memcache->set('id1','12345');

View

Memcache: get

Memcache: get-check an element from the server and return the string value of the storage element corresponding to the key or FALSE if the key fails or is not found.

Get () can be used in either of the following ways:

string Memcache::get ( string $key [, int &$flags ] )array Memcache::get ( array $keys [, array &$flags ] )

If the server has an element that uses the key as the key for storage, the Memcache: get () method returns the previously stored value. You can also give Memcache: get () to obtain the element value of an array. The returned array only contains the key-value pair found from the server.

The get method includes two parameters. The first parameter key indicates the key or key array for obtaining the value. The second parameter is flags. If this parameter is specified (passed as a reference ), this parameter is written with the corresponding key information. These tags have the same meaning as the parameters of the same name in the Memcache: set () method. The internal usage of pecl/memcache is retained with the low position of the int value (for example, it is used to describe the compression and serialization status)

$memcache->set('id1','11111');$memcache->add('id2','22222');echo $memcache->get('id1') ."<br>";//11111echo $memcache->get(['id1','id2'])['id2'];//22222

 

Distributed

If there are multiple memcached servers, you 'd better use Memcache: addServer () to connect to the server, instead of using Memcache: connect () to connect to the memcached server, because the PHP client uses the server pool, according to the "crc32 (key) % current_server_num" hash algorithm, the key is hashed to different servers. The format of the Memcache: addServer () method is as follows:

bool Memcache::addServer ( string $host [, int $port = 11211 [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback [, int $timeoutms ]]]]]]]] )

Memcache: addServer () adds a server to the connection pool. Connections opened through Memcache: addServer () will be automatically closed after the script is executed. You can also use Memcache: close () to manually close the connection. You can also use memcache_add_server () to add servers

When this method is used (opposite to Memcache: connect () and Memcache: pconnect (), the network connection will not be established immediately, but will not be established until it is actually used. Therefore, when a large number of servers are added to the connection pool, there is no overhead because they may not be used.

Failover may occur at any level of the method. As long as other servers are available, users will not feel it. Any socket or memcache server-level errors (such as memory overflow) may cause failover. A common client error, such as using Memcache: add to try to add an existing key, will not cause failover.

The host parameter indicates the host location of the memcached server to be connected. This parameter usually specifies other types of transmission. For example, the Unix domain socket uses unix: // path/to/memcached. sock. In this case, the port must be set to 0.

The port parameter indicates the port that the memcached server listens. Set to 0 when using UNIX domain socket connection

The persistent parameter is used to control whether persistent connections are used. TRUE by default

The weight parameter indicates the number of buckets created for this server. It is used to control the weight of the selected server. The probability of a single server being selected is relative to the total weight of all servers.

The timeout parameter indicates the connection duration (timeout) in seconds. The default value is 1 second.

The retry_interval parameter indicates the Retry Interval when the server connection fails. The default value is 15 seconds. If this parameter is set to-1, no Retry is performed. This parameter and persistent parameter are invalid when the extension is dynamically loaded using the dl () function.

Each failed connection structure has its own timeout time. If you select a backend service request before it expires, the structure will be skipped. Once a connection fails, it will be successfully reconnected or marked as a failed connection to reconnect in the next retry_interval second. The typical impact is that each web service sub-process will try to reconnect every retry_interval second when serving a page.

The status parameter is used to control whether the server can be marked as online. When this parameter is set to FALSE and the retry_interval parameter is set to-1, the failed server can be kept in a pool to avoid affecting the key allocation algorithm. Requests from this server fail over or immediately fail, which is limited by the settings of the memcache. allow_failover parameter. This parameter defaults to TRUE, indicating that failover is allowed.

The failure_callback parameter allows you to specify a callback function after an error occurs during running. The callback function runs before the Failover. The callback function accepts two parameters: host name and port number of the failed host.

<? Php // instantiate the object $ memcache = new Memcache; // connect to the memcache server $ memcache-> addServer ('localhost'); $ memcache-> addServer ('123. 168.1.2 '); $ memcache-> addServer ('2017. 168.1.3 '); for ($ I = 0; $ I <100; $ I ++) {$ memcache-> set ('key '. $ I, md5 ($ I), 0, 60) ;}// close the connection $ memcache-> close ();?>

 

Status

Memcache: getStats

Memcache: getStats-Get server statistics

array Memcache::getStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

Memcache: getStats () returns the server statistics of an associated data. The array key is the statistical information name, and the value is the statistical information value. You can also use the memcache_get_stats () function ()

The type parameter indicates the type of statistics to be captured. The values available include {reset, malloc, maps, cachedump, slabs, items, and sizes }. The memcached protocol is used to specify these additional parameters to facilitate memcache developers (check for changes)

The slabid parameter is used to copy data from a specified slab Block in conjunction with the parameter type. The cachedump command takes full use of the server and is usually used for strict debugging.

The limit parameter is used in combination with the parameter type to set the number of objects retrieved from the server during cachedump.

<? Php // instantiate the object $ memcache = new Memcache; // connect to the memcache server $ memcache-> addServer ('localhost '); /* Array ([pid] => 6268 [uptime] => 3054571472 [time] => 240596173 [version] => 1.4.4-14-g9c660c0 [pointer_size] => 64 [curr_connections] => 13 [total_connections] => 24 [connection_structures] => 14 [Response _get] => 37 [Response _set] => 526 [Response _flush] => 1 [get_hits] => 31 [get_misses] => 6 [delete_misses] => 0 [delete_hit S] => 2 [incr_misses] => 0 [incr_hits] => 0 [decr_misses] => 0 [decr_hits] => 0 [cas_misses] => 0 [cas_hits] => 0 [cas_badval] => 0 [auth_cmds] => 0 [auth_errors] => 0 [bytes_read] => 27834 [bytes_written] => 9658 [limit_maxbytes] => 67108864 [accepting_conns] => 1 [listen_disabled_num] => 0 [threads] => 4 [conn_yields] => 0 [bytes] => 10655 [curr_items] => 105 [total_items] => 518 [evictions] => 0) */print_r ($ memcache-> getStats (); // close the connection $ memcache-> close ();?>

Memcache: getExtendedStats

Memcache: getExtendedStats-statistics on all servers in the cache server pool

array Memcache::getExtendedStats ([ string $type [, int $slabid [, int $limit = 100 ]]] )

Memcache: getExtendedStats () returns server statistics for a two-dimensional association. The array key is composed of the host: port mode. The statistical information returned by Invalid servers is set to false. Similarly, you can use the memcache_get_extended_stats () function ()

The type parameter indicates the type of statistics to be captured. The values available include {reset, malloc, maps, cachedump, slabs, items, and sizes }. The memcached protocol is used to specify these additional parameters to facilitate memcache developers (check for changes)

The slabid parameter is used to copy data from a specified slab Block in conjunction with the parameter type. The cachedump command takes full use of the server and is usually used for strict debugging.

The limit parameter is used in combination with the parameter type to set the number of objects retrieved from the server during cachedump.

<?php    $memcache_obj = new Memcache;    $memcache_obj->addServer('memcache_host', 11211);    $memcache_obj->addServer('failed_host', 11211);        $stats = $memcache_obj->getExtendedStats();/*Array(    [memcache_host:11211] => Array        (            [pid] => 3756            [uptime] => 603011            [time] => 1133810435            [version] => 1.1.12            [rusage_user] => 0.451931            [rusage_system] => 0.634903            [curr_items] => 2483            [total_items] => 3079            [bytes] => 2718136            [curr_connections] => 2            [total_connections] => 807            [connection_structures] => 13            [cmd_get] => 9748            [cmd_set] => 3096            [get_hits] => 5976            [get_misses] => 3772            [bytes_read] => 3448968            [bytes_written] => 2318883            [limit_maxbytes] => 33554432        )    [failed_host:11211] => false) */        print_r($stats);?>

 

Security

Access to the MYSQL database server must pass user authentication before access, and access to the memcached server is directly connected through the client, without any verification process. In this way, if the server is directly exposed to the Internet, it is dangerous. If the server is light, the data leakage will be viewed by other irrelevant persons, and the server will be infiltrated. To ensure security, we have the following two security measures:

  1. Intranet access

It is best to set the access between the two servers to the Intranet, generally between the Web server and the Memcache server. Generally, the server has two NICs, one pointing to the Internet and the other pointing to the Intranet. Therefore, the Web server is allowed to access the Memcache server through the Intranet Nic. When the Memcache server is started, listen to the Intranet IP address and port, and access between the Intranet can effectively prevent other illegal access

# memcached -d -m 1024 -u root -l 192.168.0.200 -p 11211 -c 1024 start

The Memcache server sets listening to port 11211 of the ip address 192.168.0.200 over the Intranet, occupying 1024 MB of memory and allowing a maximum of concurrent connections.

  2. Set a firewall

Firewall is a simple and effective method. If memcache and web Server are on the same machine or access Memcache through an Internet IP address, you need to use a firewall or proxy program to filter out illegal access.

In Linux, you can use iptables or FreeBSD ipfw to specify rules to prevent unauthorized access. For example, you can set to allow only Web servers to access the Memcache server and prevent other accesses.

# iptables -F# iptables -P INPUT DROP# iptables -A INPUT -p tcp -s 192.168.0.2 –dport 11211 -j ACCEPT# iptables -A INPUT -p udp -s 192.168.0.2 –dport 11211 -j ACCEPT

The above iptables rule only allows access from the Web server 192.168.0.2 to the Memcache server. It can effectively prevent some illegal access and add other rules to enhance security, this can be done according to your own needs.

 

Application

The most common memcache application in a project is to cache the data results queried from the database and save session control information. Session control will be introduced later. The following describes how to use the memcache server to cache the database query results to reduce the pressure on the database caused by frequent database connections and a large number of queries. The design principle is that as long as the records in the database are not changed, you do not need to reconnect to the database and execute repeated query statements repeatedly. The same query results should be obtained from the cache server.

<? Php function select ($ SQL, MemCache $ memcache) {$ key = md5 ($ SQL); $ data = $ memcache-> get ($ key); if (! $ Data) {try {$ pdo = new PDO ("mysql: host = localhost; dbname = xsphp", "root", "123456");} catch (PDOException $ e) {die ("Database Connection Failed :". $ e-> getMessage ();} $ stmt = $ pdo-> prepare ($ SQL); $ stmt-> execute (); $ data = $ stmt-> fetchAll (PDO: FETCH_ASSOC); $ memcache-> add ($ key, $ data, MEMCACHE_COMPRESSED, 0);} return $ data ;} $ memcache = new Memcache; $ memcache-> connect ("localhost", 11211); $ data = select ("SELE CT * FROM user ", $ memcache); var_dump ($ data); $ memcache-> close ();?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.