`

Memcache入门

阅读更多

 1       Memcache是什么

Memcachedanga.com的一个项目,最早是为 LiveJournal 服务的,目前全世界不少人使用这个缓存项目来构建自己大负载的网站,来分担数据库的压力。

它可以应对任意多个连接,使用非阻塞的网络IO。由于它的工作机制是在内存中开辟一块空间,然后建立一个HashTableMemcached自管理这些HashTable

   

为什么会有Memcachememcached两种名称?

其实Memcache是这个项目的名称,而memcached是它服务器端的主程序文件名,

    

Memcache官方网站:http://www.danga.com/memcached

 

2       Memcache工作原理

首先 memcached 是以守护程序方式运行于一个或多个服务器中,随时接受客户端的连接操作,客户端可以由各种语言编写,目前已知的客户端 API 包括 Perl/PHP/Python/Ruby/Java/C#/C 等等。客户端在与 memcached 服务建立连接之后,接下来的事情就是存取对象了,每个被存取的对象都有一个唯一的标识符 key,存取操作均通过这个 key 进行,保存到 memcached 中的对象实际上是放置内存中的,并不是保存在 cache 文件中的,这也是为什么 memcached 能够如此高效快速的原因。注意,这些对象并不是持久的,服务停止之后,里边的数据就会丢失。

 

与许多 cache 工具类似,Memcached 的原理并不复杂。它采用了C/S的模式,在 server 端启动服务进程,在启动时可以指定监听的 ip,自己的端口号,所使用的内存大小等几个关键参数。一旦启动,服务就一直处于可用状态。Memcached 的目前版本是通过C实现,采用了单进程,单线程,异步I/O,基于事件 (event_based) 的服务方式.使用 libevent 作为事件通知实现。多个 Server 可以协同工作,但这些 Server 之间是没有任何通讯联系的,每个 Server 只是对自己的数据进行管理。Client 端通过指定 Server 端的 ip 地址(通过域名应该也可以)。需要缓存的对象或数据是以 key->value 对的形式保存在Server端。key 的值通过 hash 进行转换,根据 hash 值把 value 传递到对应的具体的某个 Server 上。当需要获取对象数据时,也根据 key 进行。首先对 key 进行 hash,通过获得的值可以确定它被保存在了哪台 Server 上,然后再向该 Server 发出请求。Client 端只需要知道保存 hash(key) 的值在哪台服务器上就可以了。

 

        其实说到底,memcache 的工作就是在专门的机器的内存里维护一张巨大的 hash 表,来存储经常被读写的一些数组与文件,从而极大的提高网站的运行效率。

 

 

 

今天先研究研究缓存工具类的改造,在旧框架中部分函数用了ehcache对执行结果进行了缓存处理,现在目标是提供一个缓存工具类,在配置文件中配置使用哪种缓存(memcached或ehcached),使其它程序对具体的缓存不依赖,同时使用AOP方式来对方法执行结果进行缓存。
首先是工具类的实现:
在Spring中配置

Java代码 复制代码
  1. <!-- EhCache Manager -->   
  2. <bean id="cacheManager"  
  3.     class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">   
  4.     <property name="configLocation">   
  5.         <value>classpath:ehcache.xml</value>   
  6.     </property>   
  7. </bean>   
  8.   
  9. <bean id="localCache"  
  10.     class="org.springframework.cache.ehcache.EhCacheFactoryBean">   
  11.     <property name="cacheManager" ref="cacheManager" />   
  12.     <property name="cacheName"  
  13.         value="×××.cache.LOCAL_CACHE" />   
  14. </bean>   
  15.   
  16. <bean id="cacheService"  
  17.     class="×××.core.cache.CacheService" init-method="init" destroy-method="destory">   
  18.     <property name="cacheServerList" value="${cache.servers}"/>   
  19.     <property name="cacheServerWeights" value="${cache.cacheServerWeights}"/>   
  20.     <property name="cacheCluster" value="${cache.cluster}"/>   
  21.     <property name="localCache" ref="localCache"/>   
  22. </bean>  

在properties文件中配置${cache.servers} ${cache.cacheServerWeights} ${cache.cluster}
具体工具类的代码

Java代码 复制代码
  1. /**  
  2.  * @author Marc  
  3.  *   
  4.  */  
  5. public class CacheService {   
  6.     private Log logger = LogFactory.getLog(getClass());   
  7.   
  8.     private Cache localCache;   
  9.   
  10.     String cacheServerList;   
  11.   
  12.     String cacheServerWeights;   
  13.   
  14.     boolean cacheCluster = false;   
  15.   
  16.     int initialConnections = 10;   
  17.   
  18.     int minSpareConnections = 5;   
  19.   
  20.     int maxSpareConnections = 50;   
  21.   
  22.     long maxIdleTime = 1000 * 60 * 30// 30 minutes   
  23.   
  24.     long maxBusyTime = 1000 * 60 * 5// 5 minutes   
  25.   
  26.     long maintThreadSleep = 1000 * 5// 5 seconds   
  27.   
  28.     int socketTimeOut = 1000 * 3// 3 seconds to block on reads   
  29.   
  30.     int socketConnectTO = 1000 * 3// 3 seconds to block on initial   
  31.                                     // connections. If 0, then will use blocking   
  32.                                     // connect (default)   
  33.   
  34.     boolean failover = false// turn off auto-failover in event of server   
  35.                                 // down   
  36.   
  37.     boolean nagleAlg = false// turn off Nagle's algorithm on all sockets in   
  38.                                 // pool   
  39.   
  40.     MemCachedClient mc;   
  41.   
  42.     public CacheService(){   
  43.         mc = new MemCachedClient();   
  44.         mc.setCompressEnable(false);   
  45.     }   
  46.     /**  
  47.      * 放入  
  48.      *   
  49.      */  
  50.     public void put(String key, Object obj) {   
  51.         Assert.hasText(key);   
  52.         Assert.notNull(obj);   
  53.         Assert.notNull(localCache);   
  54.         if (this.cacheCluster) {   
  55.             mc.set(key, obj);   
  56.         } else {   
  57.             Element element = new Element(key, (Serializable) obj);   
  58.             localCache.put(element);   
  59.         }   
  60.     }   
  61.     /**  
  62.      * 删除   
  63.      */  
  64.     public void remove(String key){   
  65.         Assert.hasText(key);   
  66.         Assert.notNull(localCache);   
  67.         if (this.cacheCluster) {   
  68.             mc.delete(key);   
  69.         }else{   
  70.             localCache.remove(key);   
  71.         }   
  72.     }   
  73.     /**  
  74.      * 得到  
  75.      */  
  76.     public Object get(String key) {   
  77.         Assert.hasText(key);   
  78.         Assert.notNull(localCache);   
  79.         Object rt = null;   
  80.         if (this.cacheCluster) {   
  81.             rt = mc.get(key);   
  82.         } else {   
  83.             Element element = null;   
  84.             try {   
  85.                 element = localCache.get(key);   
  86.             } catch (CacheException cacheException) {   
  87.                 throw new DataRetrievalFailureException("Cache failure: "  
  88.                         + cacheException.getMessage());   
  89.             }   
  90.             if(element != null)   
  91.                 rt = element.getValue();   
  92.         }   
  93.         return rt;   
  94.     }   
  95.     /**  
  96.      * 判断是否存在  
  97.      *   
  98.      */  
  99.     public boolean exist(String key){   
  100.         Assert.hasText(key);   
  101.         Assert.notNull(localCache);   
  102.         if (this.cacheCluster) {   
  103.             return mc.keyExists(key);   
  104.         }else{   
  105.             return this.localCache.isKeyInCache(key);   
  106.         }   
  107.     }   
  108.     private void init() {   
  109.         if (this.cacheCluster) {   
  110.             String[] serverlist = cacheServerList.split(",");   
  111.             Integer[] weights = this.split(cacheServerWeights);   
  112.             // initialize the pool for memcache servers   
  113.             SockIOPool pool = SockIOPool.getInstance();   
  114.             pool.setServers(serverlist);   
  115.             pool.setWeights(weights);   
  116.             pool.setInitConn(initialConnections);   
  117.             pool.setMinConn(minSpareConnections);   
  118.             pool.setMaxConn(maxSpareConnections);   
  119.             pool.setMaxIdle(maxIdleTime);   
  120.             pool.setMaxBusyTime(maxBusyTime);   
  121.             pool.setMaintSleep(maintThreadSleep);   
  122.             pool.setSocketTO(socketTimeOut);   
  123.             pool.setSocketConnectTO(socketConnectTO);   
  124.             pool.setNagle(nagleAlg);   
  125.             pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);   
  126.             pool.initialize();   
  127.             logger.info("初始化memcached pool!");   
  128.         }   
  129.     }   
  130.   
  131.     private void destory() {   
  132.         if (this.cacheCluster) {   
  133.             SockIOPool.getInstance().shutDown();   
  134.         }   
  135.     }   
  136. }  


然后实现函数的AOP拦截类,用来在函数执行前返回缓存内容

Java代码 复制代码
  1. public class CachingInterceptor implements MethodInterceptor {   
  2.   
  3.     private CacheService cacheService;   
  4.     private String cacheKey;   
  5.   
  6.     public void setCacheKey(String cacheKey) {   
  7.         this.cacheKey = cacheKey;   
  8.     }   
  9.   
  10.     public void setCacheService(CacheService cacheService) {   
  11.         this.cacheService = cacheService;   
  12.     }   
  13.   
  14.     public Object invoke(MethodInvocation invocation) throws Throwable {   
  15.         Object result = cacheService.get(cacheKey);   
  16.         //如果函数返回结果不在Cache中,执行函数并将结果放入Cache   
  17.         if (result == null) {   
  18.             result = invocation.proceed();   
  19.             cacheService.put(cacheKey,result);   
  20.         }   
  21.         return result;   
  22.     }   
  23. }  

Spring的AOP配置如下:

Java代码 复制代码
  1. <aop:config proxy-target-class="true">   
  2.         <aop:advisor   
  3.             pointcut="execution(* ×××.PoiService.getOne(..))"  
  4.             advice-ref="PoiServiceCachingAdvice" />   
  5.     </aop:config>   
  6.   
  7.     <bean id="BasPoiServiceCachingAdvice"  
  8.         class="×××.core.cache.CachingInterceptor">   
  9.         <property name="cacheKey" value="PoiService" />   
  10.         <property name="cacheService" ref="cacheService" />   
  11.     </bean>  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics