Windows configuration Memcache methods

Source: Internet
Author: User
Tags flush memcached php tutorial iptables port number

Before I have written a "PHP implementation of multiple server sharing session data" article, the text of the session is used to save the database tutorial, in a large number of concurrent visits, the server load will be very large, often exceeding the maximum MySQL connection, using memcached, We can solve this problem very well, the working principle is as follows:

When the user accesses the Web page, see if there is a session data for the current user in the memcached, use session_id () as the unique identifier, or if the data exists, return directly if it does not exist, then make a database connection, get the session data, and save the data to Memcached, for next use;
At the end of the current PHP run (or Session_write_close ()), the My_sess::write () method is invoked to write the data to the database, so that each time there is still a database operation, the method needs to be optimized. Use a global variable to record the session data when the user enters the page, and then compare the data in the write () method with the same session data that you want to write, to make a database connection, write to the database, and delete the corresponding object in the memcached. If the same, it means that the session data has not changed, so you can do nothing, directly returned;
Then how to solve the user session expiration time? Remember the memcached Add () method has an expiration time parameter $exp? The parameter value is set to less than the session maximum survival time. And don't forget to give those who have been online the duration of the session, which can be resolved in the Write () method, and the database data is updated by judging the time and complying with the criteria.

Today we're going to look at the Memcached method under win.

After you extract the Memcache Server installation package to the C:memcached folder, install it using the CMD command window.

1> Start > Run: CMD (OK)

2>CD c:memcached (carriage return)

3>memcached-d Install (enter this step to perform the installation)

4>memcached-d Start (Enter this step to start the Memcache server, the default allocation of 64M memory, use 11211 port)

The Memcache server is now ready to use.


Run on service side:
#./memcached-d-M 2048-l 10.0.0.40-p 11211
This will start a process that consumes 2G of memory and open port 11211 to receive requests. Because 32-bit systems can handle only 4G of memory addressing, 2-3 processes can be run on 32-bit servers that use PAE greater than 4G memory and are monitored on different ports.

Another example: memcached-d-M 10-u root-l 192.168.105.73-p 12000-c 256-p

The-D option is to start a daemon,
-M is the amount of memory allocated to Memcache, in megabytes, I am 10MB here,
-U is the user running memcache, I am here root,
-L is a listening server IP address, if there are more than one address, I specify the IP address of the server 192.168.105.73,
-P is the port that sets the memcache listening, I set 12000 here, preferably 1024 or more ports,
The-c option is the maximum number of concurrent connections to run, the default is 1024, I set 256 here, according to the load of your server to set,
-P is set to save the Memcache pid file, which I am saving here in/tmp/memcached.pid

Memcache Server Security:

Memcache server side is directly through the client directly after the operation, without any verification process, so if the server is directly exposed to the Internet is more dangerous, light data leakage by other unrelated personnel to view, heavy server was invaded, Besides, there may be some unknown bugs or buffer overflows, which are unknown, so the danger is predictable. For the sake of safety, make two suggestions, can slightly prevent hacker's intrusion or data leakage.

Now the questions about modifying the Memcache server configuration are described below:

1> uses intranet IP to provide Web application server calls and does not allow direct calls through extranet, such as placing Memcache servers on 192.168.1.55 servers

2> modify port, such as 11200

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

The method is as follows:

1> Start > Run: CMD (OK)

2>CD c:memcached (carriage return)

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

Note that the command line does not return to the c:memcached> state at this time, and the Memcache server is actually silently turned into a stop state. This window cannot be closed. Open a new CMD window

4> Start > Run: CMD (OK)

5>CD c:memcached (carriage return)

6>memcached-d Start (enter) to close this cmd window.

You can use the newly configured Memcache server at this time.


Although the above method solves the problem of modifying the default configuration, there will always be a CMD window that cannot be closed, or 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

The value of the default ImagePath key for 3> 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 key) > Admin > Service find memcache Service, reboot once can take effect.


At this point, the same network segment of the computer can still use this memcache server, we limit the specified Web application server to be able to use the way through the firewall. If only allow 192.168.1.2 this Web server access to the Memcache server, can effectively prevent some illegal access, the corresponding can also add some other rules to enhance security, this can be done according to their own needs.

Memcache server side is directly through the client directly after the operation, without any verification process, so if the server is directly exposed to the Internet is more dangerous, light data leakage by other unrelated personnel to view, heavy server was invaded, because the Mecache is run with root permissions, Besides, there may be some unknown bugs or buffer overflows, which are unknown, so the danger is predictable. To be on the safe side, I make two suggestions that can be a little bit of protection against hacking or data leaks.

Intranet access
It is best to access the two servers in the intranet form, typically between the Web server and the Memcache server. Universal servers are two network cards, a point to the Internet, a point to the intranet, then let the Web server through the intranet network card to access the Memcache server, we memcache the server on the start of the monitoring intranet IP address and port, 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
Memcache server-side setup listens to 11211 ports of 192.168.0.200 IP through the intranet, consumes 1024MB of RAM, and allows maximum 1024 concurrent connections

Setting up Firewalls
Firewall is a simple and effective way, if it is two servers are hanging in the net, and need to access memcache through the extranet IP, then you can consider using a firewall or agent program to filter illegal access.
In general, we can use Iptables or FreeBSD under Linux to specify some rules to prevent illegal access, such as we can set up only 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 iptables rule above is to allow only 192.168.0.2 this Web server access to the Memcache server, can effectively prevent some illegal access, the corresponding can also add some other rules to enhance security, this can be done according to their own needs


Many times you need to monitor the memcached running on the server, such as the number of cached queries, the hit rate, and so on. But found the
That Memcached-tool was written in Perl under Linux, and I didn't try to use Windows. Then find a simple way to do that is to use Telnet.

1, Windows system connection memcached port cmd command line type telnet 192.168.1.1 11211 11211 is the memcached bound port number.
2, connect the upper port and enter the stats command, you can get a description of the memcached server operation parameters.
STAT PID 4356 server process ID
STAT uptime 56625 Server run time, unit seconds
STAT time 1225249079 Server current UNIX times
STAT version 1.1 .0 Server version number
STAT pointer_size
STAT rusage_user 151.845489 The cumulative user time for this process (seconds: subtle)
STAT Rusage_system 121.667603 Cumulative system time for this process (sec: subtle)
STAT ibuffer_size 4096
STAT curr_connections 13 connection number
STAT total_connections 54136 Server run up Total number of connections
STAT connection_structures 318 Server assigned number of connection structures
STAT cmd_get 100595 fetch requests Total
STAT Cmd_set 6510 storage requests Total
STAT get_hits 96543 Total number of requests successfully
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 by The total number of bytes sent to the network by the Tes_written 6585596 server

1>, uptime is the number of seconds that memcached runs,
2>, Cmd_get is the number of query caches.
3>, the two data division can get the average number of requests per second cache--The recent NIUPU traffic is very low, so on average a second request more than once,
Such a bit of pressure, with file system caching as no problem, will not reflect the use of memcached superior.
4>, the following cmd_set is set the number of Key=>value. The whole memcached is a big hash, with Cmd_get not found inside
, you'll call Cmd_set into the cache.
5>, followed by Get_hits, is the number of cache hits. Cache Hit Ratio = Get_hits/cmd_get * 100%.
6>, the following get_misses numbers plus get_hits should be equal to cmd_get.
7>, and Total_itemscurr_items represents the number of key-value pairs that are now in the cache.
8>, on the map total_items = = Cmd_set = = get_misses, but when the maximum available memory, memcached will delete some content, the above equation is not established

Okay, here's the test code.

<?php Tutorial
Contains memcached class files
Require_once (' memcached-client.php ');
Option settings
$options = Array (
' Servers ' => array (' 192.168.1.1:11211′ '),//memcached service address, port, multiple array elements can be used to represent more than one memcached service
' Debug ' => true,//whether to turn on debug
' Compress_threshold ' => 10240,//compressed with more than the number of bytes of data
' 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 ';
Writing objects to the memcached
$MC->add ($key, ' some random strings ');
$val = $MC->get ($key);
echo "n". Str_pad (' $MC->add () ', 60, ' _ '). " n ";
Var_dump ($val);
Replace the object data value that has been written
$MC->replace ($key, Array (' some ' => ' haha ', ' 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 List of methods:

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::d ecrement-decrement item ' s value
Memcache::d elete-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::p connect-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

Related Article

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.