Memcache plays an important role in session sharing. Because all our data is stored here, we certainly cannot use only one Memcache. We need to cluster Memcache, I am implementing this through code. The overall idea is to read all Memcache addresses during initialization, store values in all Memcache data, and randomly read the data at a time, if no value exists, the system polls the read until the read value is a value. The specific code below.
1. Place values
/**
* Store data in Memcached
* @ Param key value
* @ Param value Object
*
* The value stored in this method will never expire in Memcached. Only when Memcached's memory is full
* Some values in Memcached are cleared based on the algorithm that is not used for the longest time.
*/
Public void setMemcached (String key, Object value ){
For (int I = 0; I <mcpool. size (); I ++)
{
MemCachedClient mc = (MemCachedClient) mcpool. get (I );
Mc. set (appName + key, value );
}
}
2. Values
/**
* Randomly search for the corresponding key value from a server
* If yes, return
* If not, all servers are traversed.
*/
Public Object getMemcached (String key ){
Int num = (Math. abs (new Random (). nextInt () % mcpool. size ();
Object object = null;
Object = (MemCachedClient) mcpool. get (num). get (appName + key );
If (object! = Null)
{
Return object;
}
For (int I = 0; I <mcpool. size (); I ++)
{
MemCachedClient mc = (MemCachedClient) mcpool. get (I );
Object = mc. get (appName + key );
If (object! = Null)
{
Return object;
}
}
Return object;
}
Note: As we all know, memcache stores all serialized values and reads them in deserialization mode. WriteObject and readObject are used here. However, because of this principle, when we store the applications of various webapps, the corresponding class file cannot be obtained, resulting in deserialization and Data Reading. The solution to this problem is provided later.
For details about Memcached, click here
Memcached: click here
Refer:
Memcached installation and startup script
Performance problems of using Memcached in PHP
Install Memcached in Ubuntu and its command explanation
Install and apply Memcached
Use Nginx + Memcached's small image storage solution
Getting started with Memcached