This article mainly introduces Memcache in PHP. starting from introduction to Memcache, it describes in detail the differences between Memcache and memcached, all PHP Memcache operation methods, and detailed explanations of each operation method, for more information, see memcache.
1. Introduction to Memcache
Memcache is a danga.com project that was first used for LiveJournal. many people around the world use this cache project to build their own websites with high load to share the pressure on databases. It can cope with any number of connections and use non-blocking network I/O. Because its working mechanism is to open up a space in the memory, and then create a HashTable, Memcached manages these HashTable, so the speed is very fast.
II. differences between Memcache and memcached
Why are there two Memcache and memcached names? In fact, Memcache is the name of this project, and memcached is the name of the main program file on its server ~~~~. One is the project name, the other is the main program file name, and many people on the Internet do not understand it, so it is mixed.
III. Memcache server and client installation
There are two steps: install the memcache server and the memcached client.
The so-called server installation is to install Memcache on the server (generally in linux) to store data.
The so-called client installation refers to php (or other programs, Memcache and other good api interfaces) to use the functions provided by Memcache on the server side. php needs to add extensions.
IV. summary of all PHP Memcache Client methods
The list of all memcache functions is as follows:
Memcache: add-add a value. if it already exists, false is returned.
Memcache: addServer-add an available server address
Memcache: close-close a Memcache object
Memcache: connect-create a Memcache object
Memcache_debug-control debugging function
Memcache: decrement-deletes the value of a saved key.
Memcache: delete-delete a key value
Memcache: flush-clear all cached data
Memcache: get-get a key value
Memcache: getExtendedStats-obtains the running system statistics of all processes in the process pool.
Memcache: getServerStatus-get the parameters of the running server
Memcache: getStats-return some running statistics of the server
Memcache: getVersion-returns the version information of the running Memcache.
Memcache: increment-adds the value of a saved key.
Memcache: pconnect-creates a persistent connection object for Memcache.
Memcache: replace-overwrite an existing key
Memcache: set-add a value. if it already exists, overwrite it.
Memcache: setCompressThreshold-compresses data larger than a certain size
Memcache: setServerParams-modify server parameters at runtime
V. decomposition of PHP Memcache operations
Memcache: add usage
The code is as follows: bool Memcache: add (string $ key, mixed $ var [, int $ flag [, int $ expire])
Note:
If $ key does not exist, use this function to store the value of $ var. The function with the same functions is memcache_add ().
Parameters:
$ Key: the key value to be stored.
$ Var: the stored values, values, and integer types are saved based on the original values. Other types are automatically serialized and saved.
$ Flag: whether to use MEMCACHE_COMPRESSED to compress the stored value. true indicates compression, and false indicates no compression.
$ Expire: the expiration time of the stored value. if it is 0, it indicates that it will not expire. you can use a unix timestamp or description to indicate the time from now on, however, when you use the number of seconds, do not exceed 2592000 seconds (30 days ).
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned. If the $ key value already exists, FALSE is returned. In other cases, the usage of Memcache: add () is similar to that of Memcache: set ().
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ("localhost", 11211 );
Memcache_add ($ memcache_obj, 'Var _ key', 'Test variable', false, 30 );
$ Memcache_obj-> add ('Var _ key', 'Test variable', false, 30 );
?>
Memcache: addServer usage
The code is as follows: bool Memcache: addServer (string $ host [, int $ port [, bool $ persistent [, int $ weight [, int $ timeout [, int $ retry_interval [, bool $ status [, callback $ failure_callback])
Note:
Add an available server address to the connection pool, and enable the connection with Memcache: addServer. the connection is automatically closed after the script is executed, or you can use Memcache: close () to manually close the connection pool. The same function is memcache_add_server ().
When this method is used (compared with the Memcache: connect () and Memcache: pconnect () methods), the network connection is established only when necessary, therefore, the system load will not be increased because many servers are added to the connection pool, because many servers may not be used.
Fault recovery will occur at any stage of the method execution. as long as other servers are normal, the failed users of these connection requests will not notice it. Any socket or memcached server-level error can trigger fault recovery. Normal client errors, such as adding an existing key value, will not cause fault recovery.
Parameters:
$ Host server address
$ Port server port
$ Persistent is a persistent connection
$ Weight of this server among all servers
$ Timeout connection duration
$ Retry_interval specifies the retry interval of the connection. the default value is 15. if the value is-1, no retry is performed.
$ Status controls the online status of the server
$ Failure_callback allows you to set a callback function to handle error messages.
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows: $ Memcache = new Memcache;
$ Memcache-> addServer ('memcache _ host', 11211 );
$ Memcache-> addServer ('memcache _ host2', 11211 );
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_add_server ($ memcache_obj, 'memcache _ host2', 11211 );
?>
Memcache: close usage
Bool Memcache: close (void)
Note:
Disable the memcache server connection. This function does not close persistent connections. persistent connections are closed only when the web server is closed or restarted. Same function memcache_close ()
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_close ($ memcache_obj );
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Memcache_obj-> close ();
?>
Memcache: connect Usage
The code is as follows: bool Memcache: connect (string $ host [, int $ port [, int $ timeout])
Note:
Open the memcached server connection and establish a connection to the memcached server. the connection opened with Memcache: connect will be automatically closed after the script is executed. You can also use Memcache: close () to close the connection. The same function is memcache_connect ().
Parameters:
$ Host: the host that points to the link memcached is listening to. this parameter has another special connection method unix: // path/to/memcached. sock, that is, the unix domain name sockets. in this case, the port must be set to 0.
$ Port: The port pointing to the link memcached is listening to. when the unix domain name sockets is used, the port must be set to 0.
$ Timeout: the number of seconds used to connect to the Daemon. when you change the default value of 1 second, consider it. if your connection is too slow, you may lose the cache advantage.
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
$ Memcache = new Memcache;
$ Memcache-> connect ('memcache _ host', 11211 );
?>
Memcache: debug
The code is as follows: bool memcache_debug (bool $ on_off)
Note:
Control the debugging function, provided that the-enable-debug option is used during php compilation, otherwise this function will not work.
Parameters:
$ On_off: true indicates that debugging is enabled, and false indicates that debugging is disabled.
Return value:
If the-enable-debug option is used during php compilation, true is returned; otherwise, false is returned.
Memcache: decrement usage
The code is as follows: int Memcache: decrement (string $ key [, int $ value])
Note:
The Memcache: decremen method is used to subtract values from a saved key. its usage is similar to that of Memcache: increment.
You can also use the memcache_decrement () function.
Parameters:
Key: name of the Key to be removed
Value: The Value to be reduced.
Return value:
If the operation succeeds, the value after reduction is returned. if the operation fails, false is returned.
Example:
The code is as follows:
$ Memcache = new Memcache;
$ Memcache-> connect ('localhost', 11211 );
$ Memcache-> set ('test _ item', 8 );
$ Memcache-> increment ('test _ item', 4 );
Echo $ memcache-> decrement ('test _ item', 7 );
// Display 5
?>
In this example, the Memcache: increment function is used together.
Memcache: delete usage
The code is as follows: bool Memcache: delete (string $ key [, int $ timeout])
Note:
Delete a key value. if the $ timeout parameter is set, the stored value will expire after the set number of seconds. you can also use the memcache_delete () function ()
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_delete ($ memcache_obj, 'Key _ to_delete ', 10 );
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Memcache_obj-> delete ('key _ to_delete ', 10 );
?>
Memcache: flush
The code is as follows: bool Memcache: flush (void)
Note:
Clear all cached data. Memcache: flush does not actually release resources. it only marks all the caches as expired, so that the new cache can overwrite the occupied memory space. The same function is memcache_flush ()
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_flush ($ memcache_obj );
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Memcache_obj-> flush ();
?>
Memcache: get
The code is as follows:
String Memcache: get (string $ key [, int & $ flags])
Array Memcache: get (array $ keys [, array & $ flags])
Note:
The function of the method is to obtain a key value. The key value can be an array and the result contains a key-value pair.
Parameters:
$ Key is the key value or the array value of a key.
$ Flags if this parameter exists, $ flags is related to the value written to this parameter. these $ flags are similar to $ flags in the Memcache: set () function.
Return value:
If the operation succeeds, the value corresponding to the key is returned. if the operation fails, false is returned.
Example:
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
$ Var = memcache_get ($ memcache_obj, 'Some _ key ');
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Var = $ memcache_obj-> get ('Some _ key ');
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
$ Var = memcache_get ($ memcache_obj, Array ('Some _ key', 'Another _ key '));
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Var = $ memcache_obj-> get (Array ('Some _ key', 'second _ key '));
?>
Memcache: getExtendedStats
The code is as follows: array Memcache: getExtendedStats ([string $ type [, int $ slabid [, int $ limit])
Note:
Obtains the running system statistics of all processes in the process pool. The same function is memcache_get_extended_stats ()
Parameters:
$ Type indicates the type to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$ Used when the first slabid parameter is set to "cachedump.
$ Limit is used when the first parameter is set to "cachedump.
Return value:
If the call succeeds, the system returns statistics. if the call fails, the system returns false.
Example:
The code is as follows:
$ Memcache_obj = new Memcache;
$ Memcache_obj-> addServer ('memcache _ host', 11211 );
$ Memcache_obj-> addServer ('failed _ host', 11211 );
$ Stats = $ memcache_obj-> getExtendedStats ();
// The slabs mechanism allocates management memory
$ Statsslab = $ memcache_obj-> getExtendedStats (slabs );
?>
Memcache: getServerStatus
The code is as follows: int Memcache: getServerStatus (string $ host [, int $ port])
Note:
Obtain the parameters of the running server. Returns the online or offline status of a server. The same function is memcache_get_server_status ()
Parameters:
$ Host: host of the connection being listened
$ Port: The port of the host that is listening to. the default value is 11211.
Return value:
The server status is returned successfully. if the server is not started, 0 is returned. if other numbers are returned, the server is started.
Example:
The code is as follows:
$ Memcache = new Memcache;
$ Memcache-> addServer ('memcache _ host', 11211 );
Echo $ memcache-> getServerStatus ('memcache _ host', 11211 );
$ Memcache = memcache_connect ('memcache _ host', 11211 );
Echo memcache_get_server_status ($ memcache, 'memcache _ host', 11211 );
?>
Memcache: getStats
The code is as follows: array Memcache: getStats ([string $ type [, int $ slabid [, int $ limit])
Note:
Return some running statistics of the server. The same function is memcache_get_stats ()
Parameters:
$ Type indicates the type to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$ Used when the first slabid parameter is set to "cachedump.
$ Limit is used when the first parameter is set to "cachedump.
Memcache: getVersion
The code is as follows: string Memcache: getVersion (void)
Note:
Returns the version information of the running Memcache instance. Same function memcache_get_version ()
Return value:
The version of the server is returned. if the version fails, false is returned.
Example:
The code is as follows:
$ Memcache = new Memcache;
$ Memcache-> connect ('memcache _ host', 11211 );
Echo $ memcache-> getVersion ();
$ Memcache = memcache_connect ('memcache _ host', 11211 );
Echo memcache_get_version ($ memcache );
?>
Memcache: increment
The code is as follows: int Memcache: increment (string $ key [, int $ value])
Adds the value of a saved key.
For usage instructions, refer to Memcache: decrement.
Memcache: pconnect
The code is as follows: bool Memcache: pconnect (string $ host [, int $ port [, int $ timeout])
Note:
Creates a persistent connection object for Memcache.
Usage is similar to Memcache: connect (). The difference is that Memcache: pconnect is a persistent connection established. This connection will not be closed either after the script is executed or when the Memcache: close () function is run. The same function as memcache_pconnect ()
Parameters:
$ Host: the host that points to the link memcached is listening to. this parameter has another special connection method unix: // path/to/memcached. sock, that is, the unix domain name sockets. in this case, the port must be set to 0.
$ Port: The port pointing to the link memcached is listening to. when the unix domain name sockets is used, the port must be set to 0.
$ Timeout: the number of seconds used to connect to the Daemon. when you change the default value of 1 second, consider it. if your connection is too slow, you may lose the cache advantage.
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
The code is as follows:
$ Memcache_obj = memcache_pconnect ('memcache _ host', 11211 );
$ Memcache_obj = new Memcache;
$ Memcache_obj-> pconnect ('memcache _ host', 11211 );
?>
Memcache: replace
The code is as follows: bool Memcache: replace (string $ key, mixed $ var [, int $ flag [, int $ expire])
Note:
Overwrites an existing key. The same function is memcache_replace ()
Parameters:
$ Key: the key value to be stored.
$ Var: the stored values, values, and integer types are saved based on the original values. Other types are automatically serialized and saved.
$ Flag: whether to use MEMCACHE_COMPRESSED to compress the stored value. true indicates compression, and false indicates no compression.
$ Expire: the expiration time of the stored value. if it is 0, it indicates that it will not expire. you can use a unix timestamp or description to indicate the time from now on, however, when you use the number of seconds, do not exceed 2592000 seconds (30 days ).
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned. If the $ key value already exists, FALSE is returned.
The code is as follows:
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_replace ($ memcache_obj, "test_key", "some variable", false, 30 );
$ Memcache_obj-> replace ("test_key", "some variable", false, 30 );
?>
Memcache: set
The code is as follows: bool Memcache: set (string $ key, mixed $ var [, int $ flag [, int $ expire])
Note:
Add a value. if it already exists, overwrite it. The same function is memcache_set ()
Parameters:
$ Key: the key value to be stored.
$ Var: the stored values, values, and integer types are saved based on the original values. Other types are automatically serialized and saved.
$ Flag: whether to use MEMCACHE_COMPRESSED to compress the stored value. true indicates compression, and false indicates no compression.
$ Expire: the expiration time of the stored value. if it is 0, it indicates that it will not expire. you can use a unix timestamp or description to indicate the time from now on, however, when you use the number of seconds, do not exceed 2592000 seconds (30 days ).
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = new Memcache;
$ Memcache_obj-> connect ('memcache _ host', 11211 );
$ Memcache_obj-> set ('Var _ key', 'some really big variable', MEMCACHE_COMPRESSED, 50 );
Echo $ memcache_obj-> get ('Var _ key ');
Memcache: setCompressThreshold
The code is as follows: bool Memcache: setCompressThreshold (int $ threshold [, float $ min_savings])
Note:
Compress data larger than a certain size. The same function is memcache_set_compress_threshold ()
Parameters:
The setCompressThreshold method has two parameters. The first parameter indicates the critical point for processing data size, and the second parameter indicates the compression ratio. the default value is 0.2.
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
$ Memcache_obj = new Memcache;
$ Memcache_obj-> addServer ('memcache _ host', 11211 );
$ Memcache_obj-> setCompressThreshold (20000, 0.2 );
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_set_compress_threshold ($ memcache_obj, 20000, 0.2 );
?>
Memcache: setServerParams
The code is as follows: bool Memcache: setServerParams (string $ host [, int $ port [, int $ timeout [, int $ retry_interval [, bool $ status [, callback $ failure_callback])
Note:
Modify server parameters at runtime. The same function is memcache_set_server_params ().
Parameters:
$ Host server address
$ Port server port
$ Timeout connection duration
$ Retry_interval specifies the retry interval of the connection. the default value is 15. if the value is-1, no retry is performed.
$ Status controls the online status of the server
$ Failure_callback allows you to set a callback function to handle error messages.
Return value:
If the call succeeds, TRUE is returned. if the call fails, FALSE is returned.
Example:
The code is as follows:
Function _ callback_memcache_failure ($ host, $ port ){
Print "memcache '$ host: $ port' failed ";
}
$ Memcache = new Memcache;
// Add a server in offline mode
$ Memcache-> addServer ('memcache _ host', 11211, false, 1, 1,-1, false );
// Set the server to online
$ Memcache-> setServerParams ('memcache _ host', 11211, 1, 15, true, '_ callback_memcache_failure ');
$ Memcache_obj = memcache_connect ('memcache _ host', 11211 );
Memcache_set_server_params ($ memcache_obj, 'memcache _ host', 11211, 1, 15, true, '_ callback_memcache_failure ');
?>
VI. comprehensive use of instances
The code is as follows:
// Connection
$ Mem = new Memcache;
$ Mem-> connect ("db.nowamagic.net", 12000 );
// Save data
$ Mem-> set ('key1', 'This is first value', 0, 60 );
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ val ."
";
// Replace data
$ Mem-> replace ('key1', 'This is replace value', 0, 60 );
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ val ."
";
// Save the array
$ Arr = array ('AAA', 'BBB ', 'CCC', 'ddd ');
$ Mem-> set ('key2', $ arr, 0, 60 );
$ Val2 = $ mem-> get ('key2 ');
Echo "Get key2 value :";
Print_r ($ val2 );
Echo"
";
// Delete data
$ Mem-> delete ('key1 ');
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ val ."
";
// Clear all data
$ Mem-> flush ();
$ Val2 = $ mem-> get ('key2 ');
Echo "Get key2 value :";
Print_r ($ val2 );
Echo"
";
// Close the connection
$ Mem-> close ();
?>
If it is normal, the browser will output:
The code is as follows:
Get key1 value: This is first value
Get key1 value: This is replace value
Get key2 value: Array ([0] => aaa [1] => bbb [2] => ccc [3] => ddd)
Get key1 value:
Get key2 value:
VII. code analysis of instance programs
Initialize a Memcache object: $ mem = new Memcache;
Connect to our Memcache server. The first parameter is the server IP address or host name, and the second parameter is the open port of Memcache: $ mem-> connect ("192.168.0.200 ", 12000 );
Save a data to the Memcache server. The first parameter is the data key used to locate a data. The second parameter is the data content to be saved. here is a string, the third parameter is a tag, which is usually set to 0 or MEMCACHE_COMPRESSED. The fourth parameter is the data validity period, which means that the data is valid during this time, the data will be cleared by the Memcache server in seconds. if it is set to 0, it will always be valid. Here we set 60, which is the one-minute validity period: $ mem-> set ('key1', 'This is first value', 0, 60 );
Get a piece of data from the Memcache server. it has only one parameter, that is, the key to get the data. here is the key1 set in the previous step. now we get the data and output it:
The code is as follows:
$ Val = $ mem-> get ('key1 ′);
Echo "Get key1 value:". $ val;
The replace method is used to replace the above key1 value. The parameters of the replace method are the same as those of the set method. However, the first parameter key1 must be the key to replace the data content, the output is as follows:
The code is as follows:
$ Mem-> replace ('key1', 'This is replace value', 0, 60 );
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ val;
Similarly, Memcache can store arrays. Below is an array saved on Memcache, which is then retrieved and output:
The code is as follows:
$ Arr = array ('AAA', 'BBB ', 'CCC', 'ddd ');
$ Mem-> set ('key2', $ arr, 0, 60 );
$ Val2 = $ mem-> get ('key2 ');
Print_r ($ val2 );
Now, you can delete a data file by using the delte interface. the parameter is a key, and the data of the key of the Memcache server can be deleted. no result is returned when the output is complete:
The code is as follows: $ mem-> delete ('key1 ');
$ Val = $ mem-> get ('key1 ');
Echo "Get key1 value:". $ val ."
";
Finally, we clear all the data stored on the Memcache server, and we will find that no data exists. Finally, the output key2 data is empty, and the connection is closed:
The code is as follows: $ mem-> flush ();
$ Val2 = $ mem-> get ('key2 ');
Echo "Get key2 value :";
Print_r ($ val2 );
Echo"
";
8. When to use Memcache and Memcache environments
Memcache websites generally have a large traffic volume. to relieve the pressure on the database, apsaradb for Memcache is used as a cache area and some information is stored in the memory, allowing quick access at the front end. The general focus is to focus on how to share the pressure on the database and distribute it. after all, the memory capacity of a single Memcache is limited. I would like to put forward my personal opinion here. without practice, you can use it as a reference.
Distributed Application
Apsaradb for Memcache originally supports distributed architectures. our client has been slightly transformed to provide better support. Our keys can be properly encapsulated. for example, for a user-based website, each User has a user ID, which can be extracted and accessed based on a fixed ID, for example, users starting with 1 are saved on the first Memcache server, and user data starting with 2 is stored on the second child Mecache server, data access is converted and accessed according to the User ID.
However, this disadvantage is that you need to determine the User ID. if the business is inconsistent or other types of applications are not suitable, you can consider it based on your actual business, or think about a more appropriate method.
Reduce database pressure
This is important. all the data is basically stored in the database. each time the database is accessed frequently, the database performance is greatly reduced and it cannot serve more users at the same time, for example, for MySQL, tables with frequent locks, let Memcache share the pressure on the database. We need a method that is relatively small and will not change the front-end on a large scale to change the current architecture.
A simple method I want to consider:
The back-end database operation module extracts all Select operations (update/delete/insert ), then, calculate the corresponding SQL statement using the corresponding hash algorithm to obtain a hash data key (such as MD5 or SHA), and then query the key in Memcache for data. if the data does not exist, it indicates that the data has not been written into the cache, so the data is extracted from the database. one is the array format, and the data is then set to Memcache. The key is the hash value of this SQL statement, then set an expiration time, for example, one hour. The data in one hour is extracted from the cache, effectively reducing the pressure on the database. The disadvantage is that the data is not real-time. after the data is modified, it cannot be displayed on the front-end in real time, and memory usage may be high. after all, the number of data in each select operation may be large, this is a factor to consider.
9. Memcache security
The above Memcache servers are directly connected through the client and there is no 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.
The code is as follows: # memcached-d-m 1024-u root-l 192.168.0.200-p 11211-c 1024-P/tmp/memcached. pid
The Memcache server monitors 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.
The code is as follows: # 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.