Introduction to memcache

巴扎黑
Release: 2023-03-14 10:24:01
Original
1641 people have browsed it

memcached is a high-performance distributed memory cache server. Developed by the development team of foreign community website LIVEJOURNAL.

Purpose of use:

Reduce the number of database accesses by caching database query results to increase the speed and scalability of dynamic web applications.

memcache is a free and open source, high-performance, distributed memory object caching system. Used to accelerate dynamic web applications and reduce database load.

Characteristics of memcahce

1. Based on C/S architecture, simple protocol

2. Based on libevent event processing {libevent is a Network library based on event triggering, suitable for multiple platforms such as windows, Linux, bsd (Unix derivative system)}

3. Built-in memory storage method

4. Client-based memcached distribution Formula

Applicable scenarios

1. Distributed deployment is required (what is distributed: If a task has 10 sub-tasks, put these 10 sub-tasks on 10 servers separately, greatly Shorten task execution time,)

2. Need to access the same data frequently

3. Need to share data

Introduction to C/S architecture

Installation startup (see PDF document)

Use of various commands

set/add/replace/delete/get/gets/cas/stats/stats items/ append/prepend/flush_all, etc.

memcahced some features and limitations

①The amount of item data that can be saved in Memcached is not limited, only the memory is enough

②Memcached single The maximum memory used by the process is 2G. To use more memory, you can open multiple Memcached processes on multiple ports

③The maximum data expiration time is 30 days. If it is set to permanent, it will also expire at this time. Constant REALTIME_MAXDELTA

④60*60*24*30 control

⑤The maximum key length is 250 bytes, larger than this length cannot be stored, constant KEY_MAX_LENGTH 250 control

⑥The maximum key length of a single item The data is 1MB. Data exceeding 1MB will not be stored. It is controlled by the constant POWER_BLOCK 1048576.

⑦It is the default slab size

⑧The maximum number of simultaneous connections is 200, through conn_init() freetotal is used to control, the maximum number of soft connections is 1024, controlled through

⑨settings.maxconns=1024⑩Parameters related to space occupation: settings.factor=1.25, settings.chunk_size=48, affecting the data occupation of slab And step by step method

Summary of all methods of PHP’s Memcache client

The list of all methods of memcache function is as follows:
Memcache::add – Add a value, If it already exists, return false
Memcache::addServer - Add a server address for use
Memcache::close - Close a Memcache object
Memcache::connect - Create a Memcache object
memcache_debug - Control the debugging function
Memcache::decrement - Subtract the value in a saved key
Memcache::delete - Delete a key value
Memcache::flush - Clear all cached data
Memcache::get - Get a key value
Memcache::getExtendedStats - Get 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 - Return the version information of the running Memcache
Memcache::increment - Add the value in a saved key
Memcache::pconnect - Create a Memcache persistent connection object
Memcache::replace - Overwrite an existing key
Memcache::set - Add a value, if it already exists, overwrite
Memcache: :setCompressThreshold – Compress data larger than a certain size
Memcache::setServerParams – Modify server parameters at runtime

Decomposition of PHP’s Memcache operation method

Memcache::add usage

The code is as follows:
bool Memcache::add ( string $key , mixed $var [, int $flag [, int $expire ]] )



Description:
If $key does not exist, use this function to store the value of $var. The functionally equivalent function is memcache_add().

Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).

Return value:
Return TRUE if successful, return FALSE if failed. If the $key value already exists, FALSE will be returned. In other cases, the usage of Memcache::add() is similar to 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 ]]]]]]] )



Description:
Add a usable server address to the connection In the pool, the connection is opened with Memcache::addServer and automatically closed after the script is executed, or it can be closed manually with Memcache::close(). The same function is memcache_add_server().
When using this method (compared to the Memcache::connect() and Memcache::pconnect() methods), the network connection will only be established when needed, so there will be no need to add many servers to the connection pool. And increase the system burden, because many servers may not be used.
Failure recovery will occur at any stage of the execution of this method. As long as other servers are normal, users will not notice the failure of these connection requests. Any kind of socket or memcached server-level error can trigger failover. Normal client errors such as adding an existing key will not trigger failover.

Parameters:
$host server address
$port server port
Whether $persistent is a persistent connection
$weightThe weight of this server among all servers
$timeout connection duration
$retry_intervalThe interval between connection retries, the default is 15, set to -1 means no retry
$status controls the online status of the server
$failure_callback allows setting A callback function to handle error messages.

Return value:
Return TRUE if successful, return FALSE if failed.

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)

Description:
Close the memcache server connection. This function will not close the long connection. The long connection will only be closed when the web server is shut down or restarted. The same function memcache_close()
Return value:
Returns TRUE if successful, returns FALSE if failed.
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 ]] )



Instructions:
Open the memcached server connection, establish a connection to the memcached server, and open it with Memcache::connect The connection 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: Points to the host of the link that memcached is listening to. This parameter will have another special connection method unix:///path/to/memcached.sock, which uses unix domain name sockets. , in this case, the port must be set to 0
$port: Point to the port of the link that memcached is listening to. In the case of unix domain name sockets, the port must be set to 0
$timeout: used to connect to the daemon Number of seconds for the process. When you change the default value of 1 second, you need to consider that if your connection is too slow, you may lose the advantages of caching.

Return value:
Return TRUE if successful, return FALSE if failed.
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)



Description:
Control the debugging function, provided that the -enable-debug option is used when php is compiled, otherwise this function will not have any effect.
Parameters:
$on_off: true means turning on debugging, false means turning off debugging
Return value:
If php uses the -enable-debug option when compiling, return true, otherwise return false

Memcache::decrement usage

The code is as follows:
int Memcache::decrement ( string $key [, int $ value ] )



Description:
Memcache::decremen method is used to subtract the value in a saved key. Its usage is similar to Memcache::increment.
You can also use the memcache_decrement() function.
Parameters:
Key: The name of the key you want to reduce
Value: The value you want to reduce.

Return value:
If successful, return the reduced value, if failed, return false.
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
?>



This example even demonstrates the Memcache::increment function.

Memcache::delete usage

The code is as follows:
bool Memcache::delete ( string $key [, int $timeout ] )



Description:
Delete a key value. If the parameter $timeout is set, the stored value will expire after the set seconds. You can also use Function memcache_delete()

Return value:
Returns TRUE if successful, returns FALSE if failed.

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)


Description:
Clear all cached data. Memcache::flush does not actually release resources, it just marks all caches as expired, so that new caches can cover the occupied memory space. The same function is memcache_flush()

Return value:
Returns TRUE if successful, returns FALSE if failed.

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 ] )


Explanation:
The function of the method is to obtain a key value. The key value can be an array, and the result will contain key-value pairs.

Parameters:
$key is the key value or an array value of a key.
$flags If this parameter exists, then $flags is related to the value written to this parameter. These $flags are similar to the $flags in the Memcache::set() function.

Return value:
If successful, return the value corresponding to the key, if failed, return false.
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 ]]] )



Description:
Get the running system statistics of all processes in the process pool. The same function is memcache_get_extended_stats()

Parameters:
$type indicates the type required to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$slabid The first parameter is set to Used when using "cachedump".
$limit is used when the first parameter is set to "cachedump".
Return value:
If successful, statistical information will be returned. If failed, false will be returned.

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 and manages memory
$statsslab = $memcache_obj->getExtendedStats(slabs);

?>




Memcache::getServerStatus

The code is as follows:
int Memcache::getServerStatus ( string $host [, int $port ] )



Description:
Get the parameters for running the server. Returns the online or offline status of a server. The same function is memcache_get_server_status()

Parameters:
$host: The host of the listening connection
$port The port of the host of the listening connection, the default is 11211

Return value:
Successfully returns the server status. If the server is not started, 0 will be returned. Other numbers indicate that 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 ]]] )



Description:
Return some running statistics of the server. The same function is memcache_get_stats()

Parameters:
$type indicates the type required to be returned: reset, malloc, maps, cachedump, slabs, items, sizes;
$slabid The first parameter setting Used when "cachedump" is used.
$limit is used when the first parameter is set to "cachedump".

Memcache::getVersion

The code is as follows:
string Memcache::getVersion (void)



Description:
Return the version information of running Memcache. The same function memcache_get_version()

Return value:
Returns the version information of the server successfully, and returns false when it fails.

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 ] )

Perform addition operation on the value in a saved key
For usage, please refer to Memcache::decrement



Memcache::pconnect


The code is as follows:

bool Memcache::pconnect ( string $host [, int $port [ , int $timeout ]] )

Instructions:
Create a Memcache persistent connection object
The usage is similar to Memcache::connect(), the difference is that Memcache: :pconnect is a persistent connection established. This connection will not be closed after the script is executed or the Memcache::close() function is run. The function identical to it is memcache_pconnect()

Parameters:
$host: Points to the host of the link that memcached is listening to. This parameter will have another special connection method unix:///path/ to/memcached.sock, that is, use unix domain name sockets. In this case, the port must be set to 0
$port: Points to the port of the link that memcached is listening to. In the case of unix domain name sockets, the port must be set. Is 0
$timeout: The number of seconds used to connect to the daemon. When you change the default value of 1 second, you need to consider that if your connection is too slow, you may lose the advantage of caching.

Return value:
Return TRUE if successful, FALSE if failed

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 ]] )


Description:
Overwrite an existing key. The same function is memcache_replace()

Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).

Return value:
Return TRUE if successful, return FALSE if failed. If the $key value already exists, FALSE will be 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 ]] )


Description:
Add a value, if it already exists, overwrite it Write. The same function is memcache_set()

Parameters:
$key: The key value to be stored.
$var: The stored value, character type and integer type will be saved as the original value, other types will be automatically serialized and saved later.
$flag: Whether to use MEMCACHE_COMPRESSED to compress the stored value, true means compression, false means no compression.
$expire: The expiration time of the stored value. If it is 0, it means it will not expire. You can use a unix timestamp or description to represent the time from now, but when you use seconds to express it, it should not exceed 2592000 seconds. (meaning 30 days).

Return value:
Return TRUE if successful, return FALSE if failed.

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 ] )


Description:
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 represents the critical point of processing data size, and the second parameter represents the compression ratio. The default is 0.2.

Return value:
Return TRUE if successful, return FALSE if failed.

Example:

The code is as follows:

$memcache_obj = new Memcache;
$memcache_obj-> addserver ('Memcache_host', 11211);
$ Memcache_obj- & GT; Setcompressthrent (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 ]]]]] )
Description:

Modify the server parameters at runtime. The same function is memcache_set_server_params().

Parameters:
$host server address
$port server port
$timeout duration of connection
$retry_interval Interval time between connection retries, default is 15, set to -1 means no retry
$status controls the online status of the server
$failure_callback allows setting a callback function to handle error messages.

Return value:
Return TRUE if successful, return FALSE if failed.

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 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');

?>



6. Comprehensive usage examples

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 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:



7. Example program code analysis
Initialize a Memcache object: $mem = new Memcache;
Connect to our Memcache server, the first one The parameter is the IP address of the server or the host name. 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 key of the data, used to locate a data, the second parameter is the data content that needs to be saved, here is a string, the third parameter is a mark, generally set to 0 or MEMCACHE_COMPRESSED. The fourth parameter is the validity period of the data, which means that the data is valid within this time. If this time has passed, the data will be cleared by the Memcache server. The unit is seconds. If it is set to 0, it will be valid forever. We set 60 here, which is the effective time of one minute: $mem->set('key1', 'This is first value', 0, 60);
Get a piece of data from the Memcache server, it has only one parameter , is the key that needs to get the data. Here is the key1 set in the previous step. Now after getting this data, output the output:


The code is as follows:
$ val = $mem->get('key1′);
echo "Get key1 value: " . $val;

Now use the replace method to replace the value of key1 above. The parameters of the replace method are the same as those of set, but the first parameter key1 must be the key to replace the data content. The final output is:

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 also save arrays. The following is an array saved on Memcache, and 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 delete a data, use the delte interface, the parameter is a key, Then you can delete the key data of the Memcache server. There is no result in the final output:


The code is as follows:
$mem->delete('key1');
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "< br />";



Finally, we clear all the data saved on the Memcache server. We will find that the data is gone. Finally, the output key2 data is empty, and finally it is closed. Connection:

The code is as follows:
$mem->flush();
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "
";




##When to use Memcache and Memcache usage environment
Websites that use Memcache generally have relatively large traffic. In order to relieve the pressure on the database, Memcache is used as a cache area to save part of the information in the memory, so that it can be quickly processed on the front end. for access. Then the general focus is on how to share database pressure and distribute it. After all, the memory capacity of a single Memcache is limited. I simply put forward my personal opinions here. I have not practiced them and should only be used as a reference.


Distributed Application
Memcache originally supports distributed, but our client has been slightly modified to provide better support. Our keys can be encapsulated appropriately and regularly. For example, for a user-based website, each user has a User ID, so it can be extracted and accessed according to a fixed ID. For example, users starting with 1 are stored in the On one Memcache server, the data of users starting with 2 is stored on the second Memcache server. The access data is first converted and accessed according to the User ID.
But this has the disadvantage that it requires judgment on the User ID. If the business is inconsistent, or other types of applications may not be so suitable, you can consider it based on your actual business, or think of a more suitable method.


Reduce database pressure
This is more important. All data are basically stored in the database. Every time the database is accessed frequently, the database will be damaged. The performance is extremely degraded and cannot serve more users at the same time. For example, MySQL locks the table very frequently, so let Memcache share the pressure on the database. We need a way to change the current architecture in a way that makes the changes relatively small and does not require large-scale changes to the front end.
A simple method I am considering:
The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then performs the corresponding hash algorithm on the corresponding SQL to calculate a Hash the data key (such as MD5 or SHA), and then use this key to find the data in Memcache. If the data does not exist, it means that it has not been written to the cache, then extract the data from the database, one is in array class format, and then Set the data into Memcache, the key is the hash value of the SQL, and then set an expiration time accordingly, such as one hour, then the data in one hour will be extracted from the cache, effectively reducing the pressure on the database. The disadvantage is that the data is not real-time. When the data is modified, it cannot be displayed on the front end in real time, and it may also occupy a large amount of memory. After all, the amount of data selected each time may be huge. This is a factor that needs to be considered.


Memcache security
Our Memcache server above operates directly after connecting to the client without any verification process, so if the server is directly exposed It is more dangerous on the Internet. At the least, the data is leaked and viewed by other unrelated people. At worst, the server is 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 dangers are 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.

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 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 the firewall
The firewall is a simple and effective way. If both servers are connected to the Internet and you need to access Memcache through the external IP, then you can Consider using a firewall or proxy to filter unauthorized 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.

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 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 strengthen security. This can be done according to your own needs.

##Actual combat

//memcached configuration

/******************************************* */
$mem_ip='127.0.0.1';
$mem_port=11211;
$mem_prefix='';
/********************************************/

/********************************************/

//session memcached configuration, please configure it to an independent memcache service (different IP or different port number),
//Several mirror stations must be set the same, otherwise it will cause session Lost
//No other program can use this service to avoid conflicts.
/********************************************/
$session_mem_ip='127.0.0.1';
$session_mem_port=11212;

function Instance_Memcached()

{
static $mem=false;
if($mem==false && isset($GLOBALS['mem_ip']) && isset($GLOBALS['mem_port']) && extension_loaded('memcache'))
{
$mem=new Memcache;
$mem->pconnect($GLOBALS['mem_ip'],$GLOBALS['mem_port']) or die('Can not connect to memcache server! ');
}
return $mem;
}

The above is the detailed content of Introduction to memcache. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!