How the PHP distributed framework uses the Memcache synchronization session tutorial

Source: Internet
Author: User
Tags hash install php ini memcached mkdir sessions zts keep alive

As for the installation configuration of memcache, we will not say that there were two better articles as follows:
The Windows 64-bit system configuration installs Memcache cache http://www.111cn.net/sys/Windows/61708. HTM
Linux system memcache installation configuration detailed http://www.111cn.net/sys/linux/81920.htm

The steps to synchronize storage sessions using Memcache in PHP distributed are as follows:

1, directly modify php.ini configuration file

Session.save_handler = memcache
Session.save_path = "tcp://127.0.0.100:11211"

2, using the. htaccess file in the directory

Php_value Session.save_handler " Memcache "
Php_value session.save_path" tcp://127.0.0.1:11211

Description: This is only for Apache, the current use of nginx more, also do not recommend this method.

3, modifying the configuration

Ini_set ("Session.save_handler", "Memcache") in the project;
Ini_set ("Session.save_path", "tcp://127.0.0.100:11211");

Above just a few simple instructions, in fact, said Han, generally speaking, do distributed, that must have server permissions, so recommend the first.





memcache distributed implementation, Memcache distributed data synchronization, memcache saving session data implementation


Distributed Introduction to Memcache The

Memcached is called a "distributed" caching server, but there is no "distributed" functionality on the server side. The server side includes only memory storage functionality, and its implementation is simple. As for the memcached distributed, it is completely implemented by the client library. This distribution is the biggest feature of memcached.

What does memcached mean by distributing it?

The word "distributed" has been used many times here, but not explained in detail. Now start with a simple introduction to its principles, the implementation of each client is basically the same.

The following assumes that the memcached server has node1~node3 three, and the application will save data with the key named "Tokyo" "Kanagawa" "Chiba" "Saitama" "Gunma".

First, add "Tokyo" to the memcached. After the "Tokyo" is passed to the client library, the algorithm implemented by the client determines the memcached server that holds the data according to the "key". When the server is selected, it commands it to save "Tokyo" and its value.

Similarly, "Kanagawa" "Chiba" "Saitama" "Gunma" are the first to select the server and then save. Next gets the saved data. The key "Tokyo" to be obtained will also be passed to the function library when it is fetched. The function library selects the server according to the "key" by the same algorithm as when the data is saved. Using the same algorithm, you can select the same server as the save, and then send the Get command. As long as the data is not deleted for some reason, the saved value can be obtained.

In this way, the different keys are saved to a different server, and the distributed memcached is realized. memcached server increased, the key will be dispersed, even if a memcached server failed to connect, and will not affect the other cache, the system can continue to run.

Php+memcache implementation distributed:

Our php pecl memcache extension can effectively solve the memcache distributed problem, the main interface is the Addserver () function, specifically on the Addserver () function of the implementation can refer to the extension source code. Now there is a second problem, that is, the inability to synchronize data, can be understood as the master/slave mechanism in MySQL, that is, if we have more than one memcache server, using the Addserver function, each server stored data is unique, That is to say, the data stored on each memcached server is not uniform, but it keeps the data.


The

configuration uses Memcache to store session data

Session.save_handler = memcache

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

or a directory of. htaccess:

php_value session.save_handler "memcache"

Php_value session.save_path  "tcp://127.0.0.1:11211"

or in one application:

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

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

Use multiple memcached servers separated by commas, and as described in the Memcache::addserver () document, you can take additional arguments "persistent", "weight", "timeout", " Retry_interval "And so on, like this:" Tcp://host1:port1?persistent=1&weight=2,tcp://host2:port2. "

Save session:

<?php
session_start ();
if (!isset ($_session[' test ')) {
$_session[' test '] = time ();
}
$_session[' TEST3 '] = time ();
Print $_session[' TEST '];
print "<br><br>";
Print $_session[' TEST3 '];
print "<br><br>";
Print session_id ();
? >



Retrieving session data from Memcache

<?php
$memcache = memcache_connect (' localhost ', 11211);
Var_dump ($memcache->get (' 19216821213c65cedec65b0883238c278eeb573e077 '));
? >



would have seen

String (Panax) "test|i:1177556731; test3|i:1177556881; "

This output proves that the session is working properly

Storing sessions with Memcache is much faster than files, and it is easier to share sessions with multiple servers, and configuring them to use the same set of memcached servers can reduce the extra effort. The disadvantage is that the session data are stored in the memory, there is a lack of persistence, but it is not a big problem for the session data.

In addition, the WS Memcached session Handler for PHP provides a way to use Session_set_save_handler to take advantage of Memcached.


Memcache installation under Linux

1. If you install by downloading the source code, you need to download the latest version of http://memcached.googlecode.com/files/memcached-1.4.13.tar.gz.

If you install it by Apt-get, you do not need to download it.

2. For memcache installation:
1). Download source code, compile and install

Memcache used libevent This library for socket processing, so also need to install the latest version of Libevent,libevent is Https://github.com/downloads/libevent/libevent /libevent-2.0.19-stable.tar.gz, if you have a libevent installed on your system, you do not need to install it.

# cd/tmp #
wget http://www.danga.com/memcached/dist/memcached-1.2.0.tar.gz #
wgethttp://www.monkey.org/~ Provos/libevent-1.2.tar.gz


2. Install Libevent First:

# tar ZXVF libevent-1.2.tar.gz
# cd libevent-1.2
#/configure--prefix=/usr
# make
# make install



Test whether the libevent has been installed.

# Ls-al/usr/lib | grep libevent
lrwxrwxrwx 1 root 17:38libevent-1.2.so.1-> libevent-1.2.so.1.0.3
-rwxr-xr-x 1 ro OT root 263546 11?? 17:38libevent-1.2.so.1.0.3
-rw-r--r--1 root 454156 17:38 libevent.a
-rwxr-xr-x 1 root root 811 11 ?? 17:38 libevent.la
lrwxrwxrwx 1 root 17:38 libevent.so-> libevent-1.2.so.1.0.3


Install Memcache

Install memcached and require the installation location of the specified libevent in the installation:

# cd/tmp
# tar ZXVF memcached-1.2.0.tar.gz
# CD memcached-1.2.0
#./configure--WITH-LIBEVENT=/USR
# make
# make Install

If there is an error in the middle, please check the errors carefully, and configure or add the corresponding libraries or paths according to the error message.

When the installation is complete, the memcached will be placed on the/usr/local/bin/memcached.

Test for successful installation of memcached:

# ls-al/usr/local/bin/mem*

-rwxr-xr-x 1 root root 137986 11?? 17:39/usr/local/bin/memcached
-rwxr-xr-x 1 rootroot 140179 11?? 17:39/usr/local/bin/memcached-debug

2) through the Apt-get installation:

sudo apt-get install memcached, recommended by this way to install, relatively simple, not prone to errors.

To start the Memcache server:

Memcached-d-M 50-p 11211-uroot

Memcached Common Startup parameter description:

-D: Start a daemon,
-M: The amount of memory allocated to Memcache, in megabytes, by default 64MB,
-U: Users running Memcache
-L: Server IP address listening
-P: Set memcache listening port, default is 11211 Note:-P (p is lowercase)
-C: Set maximum number of concurrent connections, default is 1024
-P: Set the PID file to save Memcache note:-P (P is uppercase)
-H Display Help


Installing memcache PHP extensions

Download the latest stable version of Memcache via address http://pecl.php.net/get/memcache-2.2.6.tgz.

There are two ways to install Memcache extensions for PHP:
Install the memcache extension under Linux

You can use PHP's own pecl installer
# pecl Install Memcache

Or Apt-get install PHP's memcache extension

sudo apt-get installphp5-memcache

can also be installed from the source code

# tar zxf memcache-2.2.3.tgz
# CD memcache-2.2.3
#/usr/local/servers/php5/bin/phpize
#./configure--enable-memcache=/usr/local/servers/memcached--with-php-config=/usr/local/servers/php5/bin/ Php-config--with-apxs2=/usr/sbin/apxs
# Make && Make Inst

After installation, there will be a hint like this:

Installing shared extensions:/usr/local/servers/php5/lib/php/extensions/no-debug-non-zts-20060922/


Keep this in mind, then modify the php.ini, and put

Extension_dir = "./"

Amended to

Extension_dir = "/usr/local/servers/php5/lib/php/extensions/"


and add a row

extension= "No-debug-non-zts-20060922/memcache.so"


to install the memcache extension under Windows

To find out your PHP version, download the corresponding Memcache extended version, I use the php5.2.6, download the address for http://museum.php.net/php5/ Pecl-5.2.6-win32.zip, after decompression to find its Php_memcache.dll file, placed in the PHP directory under the extension directory, and in php.ini add a line of ' Extension=php_memcache.dll '. Phpinfo to see if the installation was successful.

PHP's Memcache

Use instance:

< ?php//Connection $mem  = new Memcache;
$mem->connect ("192.168.0.200",  12000);
Save Data $mem->set (' key1 ',  ' This is first value ',  0, 60);
$val  =  $mem->get (' Key1 '); echo  "get key1 value: "  .  $val  . "
<br/> ";
Replace data $mem->replace (' key1 ',  ' This is replace value ',  0,60);
$val  =  $mem->get (' Key1 '); echo  "get key1 value: "  .  $val  . "
<br /> ";
Save Array $arr  = array (' aaa ',  ' BBB ',  ' CCC ',  ' DDD ');
$mem->set (' Key2 ',  $arr,  0, 60);
$val 2 =  $mem->get (' Key2 ');
echo  "get key2 value: ";
Print_r ($val 2);
echo  "<br />";
Delete Data $mem->delete (' Key1 ');
$val  =  $mem->get (' Key1 '); echo  "get key1 value: "  .  $val  . "
<br /> ";
Clear All data $mem->flush (); $val 2 =  $mem->geT (' Key2 ');
echo  "get key2 value: ";
Print_r ($val 2);
echo  "<br />"; Close the connection $mem->close ();?>


memcached Cluster


Magent Software Introduction

Magent is an open source memcached proxy Server Software

Address: http://code.google.com/p/memagent/

Install Magent to/usr/local/

Cd/usr/local
mkdir magent
cd magent/
wgethttp://memagent.googlecode.com/files/magent-0.5.tar.gz
Tar zxvf magent-0.5.tar.gz
/sbin/ldconfig
sed-i "s/libs =-levent/libs =-levent-lm/g" Makefile
make



magent Command parameters:
-hthis message
-U UID
-G GID
-P port, default is 11211. (0 to disable Tcpsupport)
-S Ip:port, set memcached server IP and port
-B ip:port, set backup memcached server IP andport
-l IP, local bind IP addresses, default is 0.0.0.0
-N number, set Max connections, default is 4096
-D don ' t go to background
-K Use Ketama key allocation algorithm
-f file, UNIX socket path to listen on. Defaultis off
-I number, max keep alive connections for onememcached server, default is 20
-V Verbose

Start the Magent service

Magent-u root-n 4096-l 127.0.0.1-p12000-s127.0.0.1:8086-s 127.0.0.2:8086-b 127.0.0.1 : 11213


hash algorithm of Magent

Magent adopts the principle of consistent hashing, consistent hashing as follows: First find the hash value of the memcached Server (node) and configure it to the 0~232 Circle (Continuum). The same method is then used to find the hash value of the key that stores the data and map it to the circle. Then start looking clockwise from where the data maps to, saving the data to the first server you find. If more than 232 still cannot find the server, it is saved to the first memcached server.

Add a memcached server from the state above. Remainder distributed algorithm because the server that holds the key changes dramatically, it affects the cache hit rate, but in consistent hashing, only the keys on the first server where the server is added to the continuum are affected.

Using Magent to realize distributed management of Memecache, build a set of memcache Cluster service

1, the front-end PHP access to magent with the same memcache access, do not need to make any changes, for the insertion of the key,magent will be the value of the various memcache services, only operation Magent, do not care about the backend processing
2, the Company Project application: North and South each 10 units front-end, north and south deploy a set of magent service, Mainly consider the network of telecom Netcom Access. In the north, for example, each front-end installation of the Memcached service (large memory machine can start multiple services), each front-end installation Magent service, the back-end mount the entire machine memcached service, start parameters:

Magent-p 12000-s 127.0.0.1:8086-s 127.0.0.2:8086-s 127.0.0.3:8086.......-s127.0.0.10:8086

, all front-end configurations are the same, and any one front end simply accesses the magent of the local port, and such a memcache cluster facilitates the application.

For example, the basic configuration information of the project, the early policy can only build the configuration file in the central control machine, sync to each front-end, there is no way to put the configuration information in the cache, because the memcache of the front end is not shared, a machine cache update, other machines are not updated, with the program to control the update, or there are unstable factors , and as the service increases, also not easy to manage, after deploying the magent, can solve this problem, any one front-end update data = Global Update
This deployment can also solve the application: Session sharing

magent Use examples

Start two memcached processes, 11211 and 11212 ports respectively:

Memcached-m 1-u root-d-L 127.0.0.1-p 11211

Memcached-m 1-u root-d-L 127.0.0.1-p 11212


Start two magent processes, 10000 and 11000 ports respectively:

Magent-u root-n 51200-l 127.0.0.1-p 10000-s127.0.0.1:11211-b 127.0.0.1:11212

Magent-u root-n 51200-l 127.0.0.1-p 11000-s127.0.0.1:11212-b 127.0.0.1:11211

-S is the memcached to write,-B is the memcached for backup.

Description: The test environment is implemented using different ports of magent and Memached, where magent and memached can be placed on two servers as a group in a production environment.

That is to say, two memcached can be written through magent.

magent Use

1, installation libevent:

wget http://monkey.org/~provos/libevent-1.4.13-stable.tar.gz
TAR-XZVF libevent-1.4.13-stable.tar.gz
CD libevent-1.4.13-stable
./configure--prefix=/usr/local/libevent
Make
Make install

2, installation memcached:

wget http://memcached.googlecode.com/files/memcached-1.4.4.tar.gz
TAR-XZVF memcached-1.4.4.tar.gz
CD memcached-1.4.4
./configure--prefix=/usr/local/memcached--with-libevent=/usr/local/libevent
Make
Make install
Ln-s/usr/local/libevent/lib/libevent-1.4.so.2/usr/lib/

3, compile and install Magent:

mkdir magent
CP magent-0.5.tar.gz Magent
CD magent
TAR-XZVF magent-0.5.tar.gz
/sbin/ldconfig
Sed-i "s#libs =-levent#libs =-levent-lm#g" Makefile
VI magent.c Add
#include <limits.h>
Make

First, the use of examples:

Memcached-m 1-u root-d-L 192.168.1.219-p 11211
Memcached-m 1-u root-d-L 192.168.1.219-p 11212
Memcached-m 1-u root-d-L 192.168.1.219-p 11213


Magent-u root-n 51200-l 192.168.1.219-p 12000-s 192.168.1.219:11211-s 192.168.1.219:11212-b 192.168.1.219:11213


1, respectively in 11211, 11212, 11213 ports start 3 memcached process, in the 12000 Port Open magent Agent program;

2, 11211, 11212 ports for the main memcached,11213 port for backup memcached;

3, connected to the 12000 Magent,set Key1 and set Key2, according to the hashing algorithm, Key1 is written to 11212 and 11213 ports Memcached,key2 is written to 11212 and 11213 Port memcached;

4, when the 11211, 11212-Port memcached dead, connected to the 12000-port magent fetch data, data will be removed from the 11213-port memcached.


Third, the entire testing process:

# telnet 192.168.1.219 12000
Trying 1192.168.1.219 ...
Connected to 192.168.1. 219.
Escape character is ' ^] '.
Stats
Memcached Agent v0.4
Matrix 1-> 192.168.1.219:11211, pool size 0
Matrix 2-> 192.168.1.219:11212, pool size 0
End
Set Key1 0 0 5
Reesun
STORED
Set Key2 0 0 6
Reesun1
STORED
Quit
Connection closed by foreign host.


# telnet 192.168.1.219 11211
Trying 192.168.1.219 ...
Connected to 192.168.1.219.
Escape character is ' ^] '.
Get Key1
End
Get Key2
VALUE Key2 0 6
Reesun1
End
Quit
Connection closed by foreign host.


# telnet 192.168.1.219 11212
Trying 192.168.1.219 ...
Connected to 1192.168.1.219.
Escape character is ' ^] '.
Get Key1
VALUE Key1 0 5
Reesun
End
Get Key2
End
Quit
Connection closed by foreign host.


# telnet 192.168.1.219 11213
Trying 192.168.1.219 ...
Connected to 1192.168.1.219.
Escape character is ' ^] '.
Get Key1
VALUE Key1 0 5
Reesun
End
Get Key2
VALUE Key2 0 6
Reesun1
End
Quit
Connection closed by foreign host.

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.