(转) 分布式缓存系统Memcached简介与实践

缘起: 在数据驱动的web开发中,经常要重复从数据库中取出相同的数据,这种重复极大的增加了数据库负载。缓存是解决这个问题的好办法。但是ASP.NET中的虽然已经可以实现对页面局部进行缓存,但还是不够灵活。此时Memcached或许是你想要的。

Memcached是什么?
Memcached是由Danga Interactive开发的,高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速度。

Memcached能缓存什么?
通过在内存里维护一个统一的巨大的hash表,Memcached能够用来存储各种格式的数据,包括图像、视频、文件以及数据库检索的结果等。

Memcached快么?

非 常快。Memcached使用了libevent(如果可以的话,在linux下使用epoll)来均衡任何数量的打开链接,使用非阻塞的网络I/O,对 内部对象实现引用计数(因此,针对多样的客户端,对象可以处在多样的状态), 使用自己的页块分配器和哈希表, 因此虚拟内存不会产生碎片并且虚拟内存分配的时间复杂度可以保证为O(1).。

Danga Interactive为提升Danga Interactive的速度研发了Memcached。目前,LiveJournal.com每天已经在向一百万用户提供多达两千万次的页面访问。而这 些,是由一个由web服务器和数据库服务器组成的集群完成的。Memcached几乎完全放弃了任何数据都从数据库读取的方式,同时,它还缩短了用户查看 页面的速度、更好的资源分配方式,以及Memcache失效时对数据库的访问速度。

Memcached的特点
Memcached的缓存是一种分布式的,可以让不同主机上的多个用户同时访问, 因此解决了共享内存只能单机应用的局限,更不会出现使用数据库做类似事情的时候,磁盘开销和阻塞的发生。

Memcached的使用 
 
Memcached服务器端的安装 (此处将其作为系统服务安装)
下载文件:memcached 1.2.1 for Win32 binaries (Dec 23, 2006)
    1 解压缩文件到c:/memcached
   2 命令行输入 'c:/memcached/memcached.exe -d install' 
    3 命令行输入 'c:/memcached/memcached.exe -d start' ,该命令启动 Memcached ,默认监听端口为 11211
通过 memcached.exe -h 可以查看其帮助

一个简单的测试例子

  1. package com.mapbar.util.cache;
  2. import java.util.Date;
  3. import java.util.ResourceBundle;
  4. import com.danga.MemCached.MemCachedClient;
  5. import com.danga.MemCached.SockIOPool;
  6. /**
  7.  * 使用配置文件方式的memcache组件
  8.  *
  9.  */
  10. public class Cache {
  11.  protected static ResourceBundle rb=ResourceBundle.getBundle("memcached");;
  12.  public static MemCachedClient mcc = new MemCachedClient(); 
  13.  static {
  14.   init();
  15.  }     
  16.  public static void init(){
  17.   synchronized (mcc) {  
  18.    System.out.println("init call");
  19.    String[] servers =rb.getString("cache.servers").split(",");       
  20.          
  21.          String[] strWeights =rb.getString("cache.weights").split(",");  
  22.          Integer[] weights = new Integer[strWeights.length];
  23.          for(int i=0;i<strWeights.length;i++){
  24.           weights[i]=Integer.parseInt(strWeights[i]);
  25.          }
  26.         
  27.          //创建一个实例对象SockIOPool     
  28.          SockIOPool pool = SockIOPool.getInstance();       
  29.         
  30.          // set the servers and the weights    
  31.          //设置Memcached Server    
  32.          pool.setServers( servers );       
  33.          pool.setWeights( weights );       
  34.          pool.setInitConn(Integer.parseInt(rb.getString("cache.initConn")));       
  35.          pool.setMinConn(Integer.parseInt(rb.getString("cache.minConn")));       
  36.          pool.setMaxConn(Integer.parseInt(rb.getString("cache.maxConn")));       
  37.          pool.setMaxIdle(Long.parseLong(rb.getString("cache.maxIdle")));       
  38.         
  39.          // set the sleep for the maint thread       
  40.          // it will wake up every x seconds and       
  41.          // maintain the pool size       
  42.          pool.setMaintSleep( 30 );       
  43.         
  44. //         Tcp的规则就是在发送一个包之前,本地机器会等待远程主机    
  45. //         对上一次发送的包的确认信息到来;这个方法就可以关闭套接字的缓存,    
  46. //         以至这个包准备好了就发;    
  47.          pool.setNagle( false );       
  48.          //连接建立后对超时的控制    
  49.          pool.setSocketTO( 3000 );    
  50.          //连接建立时对超时的控制    
  51.          pool.setSocketConnectTO( 0 );       
  52.         
  53.          // initialize the connection pool       
  54.          //初始化一些值并与MemcachedServer段建立连接    
  55.          pool.initialize();    
  56.          // lets set some compression on for the client       
  57.          // compress anything larger than 64k       
  58.          mcc.setCompressEnable( true );       
  59.          mcc.setCompressThreshold( 64 * 1024 );  
  60.   }
  61.  }
  62.  protected static void bulidCache(){  
  63.   
  64.         //set(key,value,Date) ,Date是一个过期时间,如果想让这个过期时间生效的话,这里传递的new Date(long date) 中参数date,需要是个大于或等于1000的值。    
  65.         //因为java client的实现源码里是这样实现的 expiry.getTime() / 1000 ,也就是说,如果 小于1000的值,除以1000以后都是0,即永不过期    
  66.         mcc.set( "test""This is a test String" ,new Date(100000));   //十秒后过期    
  67.               
  68.     }       
  69.       
  70.  protected static void output() {       
  71.         //从cache里取值    
  72.         String value = (String) mcc.get( "test" );       
  73.         System.out.println(value);        
  74.     }       
  75.            
  76.  public static void main(String[] args){       
  77.         bulidCache();      
  78.         output();           
  79.     }        
  80. }

其中在classespath下有个memcached.properties文件

内容如下:

##muti servers spilt by ,

#这里是你的memcached启动的地址
cache.servers=192.168.0.116:11211  
cache.weights=1
#memcached be used
cache.cluster=true

#set some basic pool settings       
#5 initial, 5 min, and 250 max conns       
#and set the max idle time for a conn       
#to 6 hours  6*60*60*1000
cache.initConn=5
cache.minConn=5
cache.maxConn=250
cache.maxIdle=21600000

原文地址:https://www.cnblogs.com/tangtianfly/p/2480724.html