Home > Backend Development > PHP Tutorial > How to configure memcache in windows_PHP tutorial

How to configure memcache in windows_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 17:08:09
Original
816 people have browsed it

I have written an article before called "PHP implements multi-server sharing of SESSION data". The SESSION in the article is saved using a database tutorial. When the number of concurrent visits is large, the load on the server will be very large. , often exceeding the maximum number of MySQL connections. Using memcached, we can solve this problem well. The working principle is as follows:

When a user accesses a web page, check whether there is the current user's SESSION data in memcached, and use session_id() as the unique identifier; if the data exists, it will be returned directly. If it does not exist, then connect to the database to obtain the SESSION data, and Save this data to memcached for next time use;
When the current PHP operation ends (or session_write_close() is used), the My_Sess::write() method will be called to write the data to the database. In this case, there will still be database operations every time. This method also needs to be optimized. . Use a global variable to record the SESSION data when the user enters the page, and then compare this data in the write() method to see if it is the same as the SESSION data you want to write. If they are different, connect to the database and write it to the database. At the same time, add the corresponding data in memcached. Objects are deleted. If they are the same, it means that the SESSION data has not changed, so you can return directly without doing any operation;
So how to solve the user SESSION expiration time? Remember that memcached’s add() method has an expiration time parameter $exp? Just set this parameter value to be less than the maximum survival time of SESSION. In addition, don’t forget to extend the SESSION duration for those users who are always online. This can be solved in the write() method. By judging the time, the database data will be updated if the conditions are met.

Today we will take a look at how to use memcached under win

After extracting the memcache server installation package to the C: memcached folder, use the cmd command window to install it.

1>Start>Run: CMD (OK)

2>cd C:memcached (Enter)

3>memcached -d install (Press Enter to execute the installation)

4>memcached -d start (Press Enter. This step starts the memcache server. By default, 64M memory is allocated and port 11211 is used)

At this point the memcache server can be used normally.


Run on the server:
# ./memcached -d -m 2048 -l 10.0.0.40 -p 11211
This will start a process occupying 2G of memory and open port 11211 for receiving requests. Since 32-bit systems can only handle addressing of 4G memory, 2-3 processes can be run on a 32-bit server using PAE with memory larger than 4G and listened on different ports.

Another example: memcached -d -m 10 -u root -l 192.168.105.73 -p 12000 -c 256 -P /tmp/memcached.pid

-d option is to start a daemon process,
-m is the amount of memory allocated to Memcache, in MB, here it is 10MB,
-u is the user running Memcache, I am root here,
-l is the IP address of the listening server. If there are multiple addresses, I specified the IP address of the server 192.168.105.73,
-p is to set the port Memcache listens on. I set 12000 here, preferably a port above 1024,
The -c option is the maximum number of concurrent connections that can be run. The default is 1024. I set it to 256 here. Set it according to the load of your server.
-P is to set the pid file to save Memcache. Here I save it in /tmp/memcached.pid

memcache server security:

The Memcache server operates directly after connecting to the client without any verification process. If the server is directly exposed to the Internet, it is more dangerous. At least the data will be leaked and viewed by other unrelated people, and at worst the server Intruded, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so the danger is foreseeable. For the sake of security, here are two suggestions to prevent hacker intrusion or data leakage.

Now the problem of modifying the memcache server configuration is explained as follows:

1> Use the internal network IP to provide web application server calls. Direct calls through the external network are not allowed, such as placing the memcache server on the server 192.168.1.55

2> Modify the port, such as changing it to 11200

3> Allocate memory, such as 1024M (1G memory)

The method is as follows:

1>Start>Run: CMD (OK)

2>cd C:memcached (Enter)

3>memcached -m 1024 -p 11200 -l 192.168.1.55 (Enter)

Note that the command line will not return to the C:memcached> state at this time, and in fact the memcache server quietly changes to the stop state. This window cannot be closed. Open a new cmd window

4>Start>Run: CMD (OK)

5>cd C:memcached (Enter)

6>memcached -d start (Enter) can close this cmd window.

The newly configured memcache server can now be used.


Although the above method solves the problem of modifying the default configuration, there will always be a cmd window that cannot be closed, otherwise it will return to the default configuration of port 11211.

A better solution is to modify the registry configuration of the service:

1>Start>Run: regedit (Enter)

2> Found in the registry: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesmemcached Server

3>The default ImagePath key value is: "c:memcachedmemcached.exe" -d runservice, change to: "c:memcachedmemcached.exe" -d runservice -m 512 -p 11200 -l 192.168.1.55 (OK , close the registry)

4>My Computer (right-click)>Management>Services Find the memcache service and restart it once to take effect.


At this time, computers in the same network segment can still use this memcache server, and we limit the use of the specified web application server through the firewall. For example, only allowing the 192.168.1.2 Web server to access the Memcache server can effectively prevent some illegal access. Correspondingly, you can also add some other rules to strengthen security. This can be done according to your own needs.

The Memcache server operates directly after connecting to the client without any verification process. If the server is directly exposed to the Internet, it is more dangerous. At least the data will be leaked and viewed by other unrelated people, and at worst the server Being invaded, because Mecache runs with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so the danger is foreseeable. For the sake of security, I would like to make two suggestions to prevent hacker intrusion or data leakage.

Intranet access
It is best to make the access between the two servers in the form of an intranet, usually between the Web server and the Memcache server. Common servers have two network cards, one pointing to the Internet and one pointing to the intranet. Then let the web server access the Memcache server through the intranet network card. When our Memcache server is started, it monitors the IP address and IP address of the intranet. Ports and intranet access can effectively prevent other illegal access.
# memcached -d -m 1024 -u root -l 192.168.0.200 -p 11211 -c 1024 -P /tmp/memcached.pid
The Memcache server is set to listen to the 11211 port of the 192.168.0.200 IP on the intranet, occupying 1024MB of memory, and allowing a maximum of 1024 concurrent connections

Set up firewall
Firewall is a simple and effective method. If both servers are connected to the Internet and you need to access Memcache through external IP, you can consider using a firewall or proxy program to filter illegal access.
Generally, under Linux, we can use iptables or ipfw under FreeBSD to specify some rules to prevent some illegal access. For example, we can set up to only allow our web server to access our Memcache server, while blocking other access.
# 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 the 192.168.0.2 Web server to access the Memcache server, which can effectively prevent some illegal access. Correspondingly, you can also add some other rules to enhance security. This can be done according to your own needs.


Many times it is necessary to monitor the operation of Memcached on the server, such as the number of cached queries, hit rate, etc. But found
That memcached-tool is written in perl under Linux, and I haven't tried whether it can be used in windows. Later I found a simple way to do it, which is to use Telnet.

1. Windows system connects to the memcached port. Type telnet 192.168.1.1 11211 in the cmd command line. 11211 is the port number bound to memcached.
2. After connecting to the port, enter the stats command to get the parameters describing the operation of the Memcached server.
STAT pid 4356 server process ID
STAT uptime 56625 Server running time, unit seconds
STAT time 1225249079 The current UNIX time of the server
STAT version 1.1.0 Server version number
STAT pointer_size 64
STAT rusage_user 151.845489 The accumulated user time of this process (seconds: microseconds)
STAT rusage_system 121.667603 The accumulated system time of this process (seconds: microseconds)
STAT buffer_size 4096
STAT curr_connections 13 Number of connections
STAT total_connections 54136 Total number of connections accepted since the server was running
STAT connection_structures 318 Number of connection structures allocated by the server
STAT cmd_get 100595 Total number of retrieval requests
STAT cmd_set 6510 Total number of storage requests
STAT get_hits 96543 Total number of successful requests
STAT get_misses 4052 Total number of failed requests
STAT bytes_read 4427679 The total number of bytes read by the server from the network
STAT bytes_written 6585596 The total number of bytes sent by the server to the network

1>, uptime is the number of seconds memcached runs,
2>, cmd_get is the number of times to query the cache.
3>. Divide these two data to get the average number of cache requests per second - the traffic of niupu is very low recently, so the average request is more than once per second,
With such a big pressure, it is no problem to use file system caching, but it will not reflect the advantages of using memcached at all.
4>. The cmd_set below is the number of times key=>value is set. The entire memcached is a big hash, and the content cannot be found using cmd_get
content, cmd_set will be called and written into the cache.
5>, followed by get_hits, which is the number of cache hits. Cache hit rate = get_hits/cmd_get * 100%.
6>. The following get_misses number plus get_hits should equal cmd_get.
7>, and total_itemscurr_items represents the number of key-value pairs currently in the cache.
8>. In the picture, total_items == cmd_set == get_misses, but when the maximum available memory is used up, memcached will delete some content, and the above equation will no longer hold

Okay, here’s a test code

// Contains memcached class files
require_once(‘memcached-client.php’);
// Option setting
$options = array(
‘servers’ => array(‘192.168.1.1:11211′), //The address and port of the memcached service. Multiple array elements can be used to represent multiple memcached services
‘debug’ => true, //Whether to turn on debug
‘compress_threshold’ => 10240, //Compress when the data exceeds the number of bytes
‘persistant’ => false //Whether to use persistent connections
);
// Create memcached object instance
$mc = new memcached($options);
// Set the unique identifier used by this script
$key = ‘mykey’;
// Write objects into memcached
$mc->add($key, ’some random strings’);
$val = $mc->get($key);
echo “n”.str_pad(‘$mc->add() ’, 60, ‘_’).“n”;
var_dump($val);
// Replace the written object data value
$mc->replace($key, array('some'=>'haha', 'array'=>'xxx'));
$val = $mc->get($key);
echo “n”.str_pad(‘$mc->replace() ’, 60, ‘_’).“n”;
var_dump($val);
// Delete objects in memcached
$mc->delete($key);
$val = $mc->get($key);
echo “n”.str_pad(‘$mc->delete() ’, 60, ‘_’).“n”;
var_dump($val);
?>


Memcache method list:

Memcache::add — Add an item to the server
Memcache::addServer — Add a memcached server to connection pool
Memcache::close — Close memcached server connection
Memcache::connect — Open memcached server connection
memcache_debug — Turn debug output on/off
Memcache::decrement — Decrement item’s value
Memcache::delete — Delete item from the server
Memcache::flush — Flush all existing items at the server
Memcache::get — Retrieve item from the server
Memcache::getExtendedStats — Get statistics from all servers in pool
Memcache::getServerStatus — Returns server status
Memcache::getStats — Get statistics of the server
Memcache::getVersion — Return version of the server
Memcache::increment — Increment item’s value
Memcache::pconnect — Open memcached server persistent connection
Memcache::replace — Replace value of the existing item
Memcache::set — Store data at the server
Memcache::setCompressThreshold — Enable automatic compression of large values ​​
Memcache::setServerParams — Changes server parameters and status at runtime

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629845.htmlTechArticleI have written an article before called "PHP implements multi-server sharing of SESSION data". The SESSION in the article is Saved using the database tutorial, when the number of concurrent visits is large, the service...
Related labels:
source:php.cn
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
Latest Issues
Can Windows be learned?
From 1970-01-01 08:00:00
0
0
0
Install PHP in windows environment
From 1970-01-01 08:00:00
0
0
0
zookeeper extension under windows
From 1970-01-01 08:00:00
0
0
0
Can I play vim happily on Windows?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template