Linux installation configuration memcached and enable PHP support

Source: Internet
Author: User
Tags flush json memcached php memcached socket zts


Recently in the server upper cache system, log the PHP installation memcached extension.

# Installation Service Side

Yum Install Memcached-y
I. Launchpad

Please download the latest version of Libmemcached (20150524) at Https://launchpad.net/libmemcached/+download.

Cd/tmp
wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz
Tar zxf libmemcached-1.0.18.tar.gz
CD libmemcached-1.0.18
./configure
Make
Make install

Ii. Installation of memcached extensions

Locate and install the memcached extensions for PHP in Pecl (the PHP Extension Community Library).

In pecl you can find the following two easy to confuse memcache PHP extensions, can you distinguish between them? Do you know why we use the former? Please readers of Purple star Google!
memcached PHP extension for interfacing with memcached via Libmemcached Library
Memcache memcached Extension
[Https://pecl.php.net/package/memcached] [4] The latest version is 2.2.0

Mkdir/usr/src/php-p
cd/usr/src/php
wget Https://pecl.php.net/get/memcached-O memcached-2.2.0.tgz
Tar XF memcached-2.2.0.tgz
CD memcached-2.2.0
Phpize

# We have added some new features in the configuration to support JSON and igbinary, so we can study it sometime.
./configure--enable-memcached--enable-memcached-json--enable-memcached-igbinary
Make
Make install

# Notice the final output
# Installing shared extensions:/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/
Here we move it
Move to PHP's extension directory

cp/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/*.so/usr/local/php/lib/php/extensions/

Iii. Configuring PHP.ini

Open the php.ini file that is in effect

Vim/usr/local/php/etc/php.ini

# Add the following configuration

[Memcached]
Extension=memcached.so


PHP has an extension of the operation Memcached, which provides a set of functions to operate the memcached server, and simply divide them into categories:

1. memcached connection function (Connect, pconnect)

2. memcahced action Functions (set, GET, delete, replace, flush)

3. Multi-server configuration function (Addserver)

4. State monitoring function (GetStats ...)

Below a piece of code, give you an intuitive impression: (assuming memcached installed on the 172.10.10.10, port number 12121)

$memcache = new Memcached ();
$memcahce->connect (' 172.10.10.10 ', 12121);
$memcache->set (' Key ', ' Value ');
$memcache->get (' Key ');

The above mainly completes the memcached simple operation Flow: connects the memcached server, sets the value, takes the value (' Key ' value is ' value ');

Here we need to explain the Addserver function and connect function, Addserver is to put more than one server in the connection pool, and connect will only connect a server, if you use the Addserver, then use Connect, Only one server will be used here.

After introducing the use of memcached, let me show you how to write your own PHP memcached client.

Memcached is a server-side program, we can naturally use the socket program in PHP to connect, and the corresponding communication, to complete the storage operation of data. To use PHP and memcached communication, you first need to know the Memcached communication protocol, the relevant information can be found in the memcached source code doc/protocol.txt.

Here I use get command to show you this process

This command mainly extracts data from the data, input format: Get key\r\n

If the server does not have this value, it returns: End\r\n

If this value exists, return: Value key < tags > < data length > \ r \ n Data blocks

The following code is a simple simulated client operation

$fp = Fsocketopen (' 172.10.10.10 ', 12121, $errorno, $ERRSTR, 1);
if (! $fp)
echo "$errstr";
Else
{
$out = "Get key \ r \ n";
Fwrite ($out);
while (!feof ($FP))
$str. = Fgets ($FP);
  
if (Stripos ($str, ' end ') ===0)
Exit ("NO value Find")
$arr = Implode (' \ r \ n ', $str);
echo $arr [1];
}

Simply explain the code above, use Fsocketopen to open the socket communication interface of the server, and then send it a Get key command, then obtain the returned data and parse the returned data. There is no exception to the processing, in the programming time to fill in


When we add data, if

BOOL Memcache::add (String $key, mixed $var [, int $flag [, int $expire]])

If the report expire is set to 0, it will never expire. (As long as the memcache does not reboot, it is always in the mem)

Exprie directly to the number of seconds, then the largest 30*3600*24

If you want to keep the time longer than () + days *3600*24 can


<?php

Create a Mem object instance

$mem =newmemcache;

if (! $mem->connect ("127.0.0.1", 11211)) {

Die (' Connection failed! ');

}

Increase

1. Add a String

/* IF ($mem->set (' Key1 ', "Beijing", memcache_compressed,60)) {

echo ' Add OK ';

}*/

Inquire

$val = $mem->get (' Key1 ');

Var_dump ($val);

Modify

You can use the Replace

if ($mem->replace ("Key11", ' Hello ', memcache_compressed,60)) {

Echo ' replace OK ';

}else{

Echo ' Replace no OK ';

}

Delete

echo "<br/>";

if ($mem->delete (' key14 ')) {

Echo ' key14 delete ';

}else{

Echo ' KEY14 does not exist ';

}

?>

Distributed memcached test:

<?php


There are two memcahced services on my computer.


$mem =new Memcache;


$mem->addserver (' 127.0.0.1 ', 11211);
$mem->addserver (' 127.0.0.1 ', 9999);
$mem->addserver (' 127.0.0.1 ', 9998);

Notice here, put the key1 into the 11211-port mem or
9999-Port Mem Don't worry about us, there are $mem objects themselves maintained.
if ($mem->set (' key1 ', ' hello ', memcache_compressed,300)) {
Echo ' Add ok! ';
}
if ($mem->set (' Key2 ', ' Hello2 ', memcache_compressed,300)) {
Echo ' Add ok! ';
}
if ($mem->set (' Key3 ', ' Hello3 ', memcache_compressed,300)) {
Echo ' Add ok! ';
}


?>


Summarize:

1. Mem Service data is not synchronized, the data is distributed

2. What data to put into which memcached is determined by the client's Mem object

3. When performing addserver, it is not immediately to connect the MEM service, but by calculating, hash before you decide which mem service to connect, so when you massively join the server to the connection pool, there is no extra overhead

A detailed discussion of U memcache

① life cycle

From the data into the MEM start timing, until the time is up, destroyed, if the time is 0, it means no expiration.

The memcache data were destroyed as follows:

1. Time to

2. Restart memcached Service

3. Restart the machine where the memcached service is located

4. Delete/flush Destruction of data

② how to put the session data into the memcached service.

Steps:

1. Modify the php.ini configuration file

As follows:

; [Sesson.save_handler has User|files|memcache]

Session.save_handler= Memcache

Session.save_path= "tcp://127.0.0.1:11211"

③ test One, restart Apache

Test OK

<?php

The traditional code

Session_Start ();

$_session[' name ']= ' tianlong eight department 300 ';

$_session[' city ']= ' Beijing ';

Class dog{

Public $name;

}

$dog 1=new Dog;

$dog 1->name= ' ABCDE ';

$_session[' dog ']= $dog 1;

If the session data is in Mem, then he must be session_id

Key value to add

Remove

$name =$_session[' name '];

echo "Name= $name";

echo "Sessionid=". session_id ();

Think, if the administrator, do not let us modify the php.ini file, how we deal with the session into the memcached this function, we can use a function to modify the php.ini configuration.

Code:

<?php

Ini_set ("Session.save_handler", "memcache");

Ini_set ("Session.save_path", "tcp://127.0.0.1:9999");

You can also dynamically modify other settings for php.ini by Ini_set. But he does not affect other PHP pages, and will not modify the php.ini file itself, only for this page to take effect.

Memcached vs Session Comparison

The main purpose of memcached is to speed up, so it is a stateless data. That is, data is not bound to the user.

The session data is and is bound, so it is a stateful data.

memached Security

How to use the memcached service is safe.

Protect our memcached by enabling firewalls under Windows


You can also use firewalls in Linux.

Setup Configuration Firewall

Iptables-ainput-p tcp-s 127.0.0.1-dport 11211-j ACCEPT

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.