How to configure memcache for windows _ PHP Tutorial

Source: Internet
Author: User
Configure memcache in windows. I have previously written an article titled "PHP achieves multi-server sharing SESSION data". the SESSION in this article is saved using a database tutorial. when the concurrency traffic is high, before the service, I wrote an article titled "PHP achieves multi-server sharing SESSION data". the SESSION in this article is saved using the database tutorial. when the concurrency traffic is high, the load on the server is very large and often exceeds the maximum number of connections in MySQL. using memcached, we can solve this problem well. The working principle is as follows:

When a user accesses the webpage, check whether the current user's SESSION data exists in memcached and use session_id () as the unique identifier. if the data exists, the system returns the result directly. if the data does not exist, the system connects to the database, obtain the SESSION data and save the data to memcached for the next use;
When the current PHP running ends (or session_write_close () is used), the My_Sess: write () method is called to write data to the database. in this way, database operations are still performed each 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 the data with the SESSION data to be written in the write () method, different databases are connected and written to the database. at the same time, the corresponding objects in memcached are deleted. if they are the same, the SESSION data is not changed, so no operation can be performed and the data is returned directly;
So how can we solve the user's SESSION expiration time? Do you remember that the add () method of memcached has an expiration time parameter $ exp? Set this parameter to a value smaller than the maximum SESSION survival time. In addition, do not forget to extend the SESSION duration for those users who have been 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, let's take a look at the memcached method in win.

Decompress the memcache server installation package to the C: memcached folder and use the cmd command window to install the package.

1> Start> run: CMD (OK)

2> cd C: memcached (press enter)

3> memcached-d install (press enter to execute the installation)

4> memcached-d start (press enter to start the memcache server. the default memory is 64 MB and port 11211 is used)

Now the memcache server can be used normally.


Run on the server:
#./Memcached-d-m 2048-l 10.0.0.40-p 11211
This starts a process that occupies 2 GB of memory and opens port 11211 to receive requests. Because the 32-bit system can only handle 4G memory addressing, 2-3 processes can be run on 32-bit servers with 4G memory and monitored on different ports.

Another example is 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,
-M indicates the amount of memory allocated to Memcache. the unit is MB. here I am 10 MB,
-U is the user who runs Memcache. here I am root,
-L is the IP address of the listening server. if there are multiple IP addresses, I have specified the IP address 192.168.105.73,
-P is the port for Memcache listening. I have set Port 12000 here, preferably port 1024 or above,
-The "c" option is the maximum number of concurrent connections. the default value is 1024. I have set 256 here, which is based on the load of your server,
-P is the pid file for saving Memcache. here I am saving it in/tmp/memcached. pid

Memcache server security:

The Memcache server directly performs operations after being connected through the client without any verification process. in this way, it is dangerous to directly expose the server to the Internet, if data leaks are viewed by other unrelated personnel, the server may be infiltrated. Besides, some unknown bugs or buffer overflow may exist, which are unknown to us, so the danger is foreseeable. For the sake of security, we provide two suggestions to slightly prevent hacker intrusion or data leakage.

The following describes how to modify the configuration of the memcache server:

1> web application server calls are provided using an intranet ip address. direct calls through the Internet are not allowed, for example, placing the memcache server on the server 192.168.1.55.

2> modify the port, for example, to 11200.

3> allocate memory, for example, allocate 1024 MB (1 GB memory)

The method is as follows:

1> Start> run: CMD (OK)

2> cd C: memcached (press enter)

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

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

4> Start> run: CMD (OK)

5> cd C: memcached (press enter)

6> memcached-d start (press enter) to close the cmd window.

Now you can use the newly configured memcache server.


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 (press enter)

2> in the registry, find HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesmemcached Server.

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

4> right-click my computer> Manage> Find the memcache service and restart it to take effect.


At this time, computers in the same network segment can still use this memcache server. we can only use the specified web application server through the firewall. For example, only access from the Web server 192.168.1.2 to the Memcache server can be effectively prevented from unauthorized access, and other rules can be added to enhance security, this can be done according to your own needs.

The Memcache server directly performs operations after being connected through the client without any verification process. in this way, it is dangerous to directly expose the server to the Internet, if data leaks are viewed by other unrelated personnel, the server is infiltrated because Mecache runs with the root permission. Besides, some unknown bugs or buffer overflow may exist, these are all unknown, so the danger is foreseeable. For the sake of security, I have made two suggestions to slightly prevent hacker intrusion or data leakage.

Intranet access
It is recommended that the access between the two servers is in the intranet format, 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, so that the Web server can access the Memcache server through the intranet Nic, when the Memcache server is started, it listens to the intranet IP address and port, and the 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-P/tmp/memcached. pid
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.

Set firewall
Firewall is a simple and effective method. if both servers are connected to the Internet and Memcache needs to be accessed through an Internet IP address, you can use a firewall or proxy program to filter out illegal access.
In Linux, we can use iptables or FreeBSD ipfw to specify rules to prevent unauthorized access. for example, we can set to allow only our Web servers to access our Memcache server, at the same time, other accesses are blocked.
# 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.


It is often necessary to monitor the running status of Memcached on the server, such as the number of cache queries and hit rate. But
The memcached-tool is written in perl in linux, and I have never tried whether it can be used in windows. Later, I found a simple way to do this, that is, using Telnet.

1. in windows, connect to the memcached Port. in the cmd command line, type telnet 192.168.1.1 11211 11211 as the port number bound to memcached.
2. after connecting to the port, enter the stats command to obtain the parameters that describe the running status of the Memcached server.
STAT pid 4356 server process ID
STAT uptime 56625 server running time, in seconds
STAT time 1225249079 current UNIX time of the server
STAT version 1.1.0 server version
STAT pointer_size 64
STAT rusage_user 151.845489 cumulative user time of the process (seconds: subtle)
STAT rusage_system 121.667603 accumulated system time of the process (seconds: subtle)
STAT ibuffer_size 4096
STAT curr_connections 13 connection count
STAT total_connections 54136 total number of connections received since the server was running
STAT connection_structures 318 number of connection structures allocated by the server
STAT performance_get 100595 total number of retrieved requests
STAT performance_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 total number of bytes the server reads from the network
STAT bytes_written 6585596 total number of bytes the server sends to the network

1> uptime is the number of seconds for memcached to run,
2> pai_get is the number of times the cache is queried.
3> split the two data to get the average number of requests cached per second-the recent niupu traffic is very low, so the average request is more than once per second,
With such great pressure, it is no problem to use the file system cache, and it does not reflect the advantages of using memcached.
4>. the number of times the key => value is set in the cmd_set below. The entire memcached is a large hash, which is not found by using ipv_get.
Then, it will call cmd_set to write it into the cache.
5> followed by get_hits, which is the number of cache hits. Cache hit rate = get_hits/pai_get * 100%.
6> The following get_misses number plus get_hits should be equal to pai_get.
7>, while total_itemscurr_items indicates the number of key-value pairs in the cache.
8> total_items = resource_set = get_misses on the graph. However, when the maximum available memory is used up, memcached deletes some content and the above equation is not true.

Okay. The following is the test code.

// Contains the memcached class file
Require_once ('memcached-client. php ');
// Option settings
$ Options = array (
'Servers' => array ('192. 168.1.1: 100'), // address and port of the memcached service. multiple array elements can be used to represent multiple memcached services.
'Debug' => true, // whether to enable debug
'Compress _ threshold '=> 10240, // when the number of bytes of data exceeds
'Persistant' => false // whether to use persistent connection
);
// Create a memcached object instance
$ Mc = new memcached ($ options );
// Set the unique identifier used by this script
$ Key = 'MyKey ';
// Write an object to memcached
$ Mc-> add ($ key, 'some random string ');
$ 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' => 'hahaha', 'array' => 'XXX '));
$ Val = $ mc-> get ($ key );
Echo "n". str_pad ('$ mc-> replace ()', 60, '_'). "n ";
Var_dump ($ val );
// Delete an object 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

The SESSION in this article is saved using the database tutorial. when the concurrency traffic is high, the service...

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.