Memcached is a high-performance distributed memory object Cache System for dynamic Web applications to reduce the load on hard disk databases. Based on a hashmap of a storage key/value pair, the daemon process is written in c, the client can be implemented in various languages.
Features include:
1. There is no authentication, security control, and no redundant backup mechanism. It doesn't matter if you consider the memory database.
2. The Value size can reach 128 M after 1.4.2.
3. nodes do not communicate with each other.
4. c/s communication uses text line-based format.
5. Use the LRU algorithm to manage the memory.
6. The client can implement a consistent hash algorithm to determine the distribution of data on server nodes.
7. Lazy Expiration, does not actively check data Expiration.
Schematic:
Perl:
Integer Hash values are scattered Based on the remainder
Disadvantage: After a server is added, the remainder will change greatly, so that the server that is the same as the storage cannot be obtained, thus affecting the cache hit rate.
Php implements Consistent Hashing:
First, obtain the hash value of the memcached server (node) and configure it to 0 ~ 232 of the circle (continuum. When adding data, use the same method to obtain the hash value of the key for storing the data and map it to the circle. Search clockwise from the location where the data is mapped, and save the data to the first server. If more than 232 still cannot find the server, it will be saved to the first memcached server.
We can see that only some of the affected regions are added after the server is added. Because it is originally in the hash range of node4, it becomes the range of node5.
Memcached monitoring tools can use nagios, MemcachePHP
The following describes the usage of the java client. Integration with spring is used as an example:
The memcached java client selects xmemcached, and the related packages need to be downloaded.
1. bean configuration on the client:
[Html]
<! -- XMemcached cluster configuration -->
<Bean id = "cacheManager" class = "com. cr. common. cache. base. CacheManager">
<Property name = "clnt" ref = "xMemcachedClient"/>
<Property name = "expire" value = "3600"/>
</Bean>
<Bean name = "memcachedClientBuilder" class = "net. rubyeye. xmemcached. XMemcachedClientBuilder">
<Constructor-arg>
<List>
<Bean class = "java.net. InetSocketAddress">
<Constructor-arg>
<Value> 192.168.0.110 </value>
</Constructor-arg>
<Constructor-arg>
<Value> 11211 </value>
</Constructor-arg>
</Bean>
<Bean class = "java.net. InetSocketAddress">
<Constructor-arg>
<Value> 192.168.0.111 </value>
</Constructor-arg>
<Constructor-arg>
<Value> 11211 </value>
</Constructor-arg>
</Bean>
</List>
</Constructor-arg>
<Constructor-arg>
<List>
<Value> 1 </value>
<Value> 1 </value>
</List>
</Constructor-arg>
<Property name = "connectionPoolSize" value = "30"> </property>
<Property name = "commandFactory">
<Bean class = "net. rubyeye. xmemcached. command. TextCommandFactory"> </bean>
</Property>
<Property name = "sessionLocator">
<Bean class = "net. rubyeye. xmemcached. impl. KetamaMemcachedSessionLocator">
<Constructor-arg index = "0">
<Value> true </value>
</Constructor-arg>
</Bean>
</Property>
<Property name = "transcoder">
<Bean class = "net. rubyeye. xmemcached. transcoders. SerializingTranscoder"> </bean>
</Property>
</Bean>
<Bean name = "xMemcachedClient" factory-bean = "memcachedClientBuilder"
Factory-method = "build" destroy-method = "shutdown">
<Property name = "opTimeout" value = "5000"> </property>
</Bean>
MemcachedClientBuilder completes MemcachedClientBuilder and configures the cluster nodes in constructor-arg. Then, configure the client for connection through the memcachedClient node.
CacheManger is the management class of memcached. It holds instances of xMemcachedClient and provides get and set operations. Of course, it is injected through bean.
The main code is as follows:
[Java]
Public <T> T getCache (String key ){
Try {
Log.info ("get" + key );
Return (T) (client. get (key ));
} Catch (TimeoutException e ){
Log. error (e. getMessage (), e );
} Catch (InterruptedException e ){
Log. error (e. getMessage (), e );
} Catch (MemcachedException e ){
Log. error (e. getMessage (), e );
}
Return null;
}
Public <T> boolean setCache (String key, T value ){
Try {
Log.info ("add cache:" + key );
Return client. set (key, expire, value );
} Catch (TimeoutException e ){
Log. error (e. getMessage (), e );
} Catch (InterruptedException e ){
Log. error (e. getMessage (), e );
} Catch (MemcachedException e ){
Log. error (e. getMessage (), e );
}
Return false;
}
Ii. configuration of spring AOP aspect:
[Html]
<Span style = "font-size: 12px;"> <bean id = "systemContext" class = "com. cr. common. utils. SystemContext">
<Property name = "propertiesFile"
Value = "/WEB-INF/spring/SystemContext. properties"/>
</Bean>
<! -- BeanFactory configuration -->
<Bean class = "com. cr. common. utils. BeanFactory"> </bean>
<! -- Log aspect -->
<Bean id = "logAspect"
Class = "com. cr. common. log. LogAspect">
<Property name = "orderValue" value = "1"/>
</Bean>
<! -- Cache aspect -->
<Bean id = "cacheAspect"
Class = "com. cr. common. cache. core. CacheAspect">
<Property name = "orderValue" value = "2"/>
<Property name = "cacheManager" ref = "cacheManager"/>
</Bean>
</Span> <span style = "font-size: 12px;"> <aop: aspectj-autoproxy>
<Aop: include name = "cacheAspect"/>
<Aop: include name = "logAspect"/>
</Aop: aspectj-autoproxy> </span>
The BeanFactory class defines Bean instances in the Spring container by name:
[Java]
<Span style = "font-size: 12px;"> public class BeanFactory implements ServletContextAware {
Private static ServletContext servletContext;
Public static <T> T getBean (String beanName ){
WebApplicationContext wac = WebApplicationContextUtils. getRequiredWebApplicationContext (servletContext );
Return wac. getBean (beanName );
}
@ Override
Public void setServletContext (ServletContext servletContext ){
BeanFactory. servletContext = servletContext;
}
} </Span>
In order to record the access records on the browser end, you can write a log section, and finally the declarative configuration of the Section.
The above two configuration files are managed as spring beans.
Iii. cache cropping:
[Java]
@ Aspect
Public class CacheAspect implements Ordered {
Private int orderValue = 2;
Private Cache cacheManager;
Private Logger log = Logger. getLogger (CacheAspect. class );
@ Pointcut ("@ annotation (com. cr. common. cache. core. NeedCached )")
Public void needCached (){
}
@ Around ("needCached () & args (filter ,..)")
Public Object aroundMethod (ProceedingJoinPoint pjp, QueryFilter filter)
Throws Throwable {
If (filter. getValue () = null ){
Return null;
} Www.2cto.com
// Determine whether cache is enabled
Boolean cacheEnabled = CommonUtil. parseBoolean (ContextConfig. getProperty ("cache. enabled"), false );
If (cacheEnabled ){
String md5key = MD5Util. getMD5 (filter. getValue (). toString ());
Object value = cacheManager. getCacheInfo (md5key );
Boolean flag = false; if (null! = Value) JSONObject json = new JSONObject (value. toString ());
Return json;
} Else if ("null". equals (value )){
Return null;
} Else {value = pjp. proceed ();
If (null! = Value) {// The Service Code cacheManager. setCacheInfo (md5key, value. toString () is omitted here ());
}
Return value;
}
} Else {// cache not enabled, execute Database Query
Return pjp. proceed ();
}
}
Public void setOrderValue (int orderValue ){
This. orderValue = orderValue;
}
Public int getOrder (){
Return orderValue;
}
Public int getOrderValue (){
Return orderValue;
}
Public Cache getCacheManager (){
Return cacheManager;
}
Public void setCacheManager (Cache cacheManager ){
This. cacheManager = cacheManager;
}
}
NeedCached is a custom annotation for the method that needs to execute the cache aspect. The aroundMethod is surrounded by the method containing this annotation and the method parameter contains the filter method. Because the original key exceeds 250, md5 is used as the key, and the value is jsonObect.
When querying, if there is a cache, it will be returned directly. If not, the database query will be executed, and then the cache will be set.