---
title: "Memcached初次体验"
author: "ninggy"
date: "2011-07-21T16:08:37Z"
tags: []
categories: ["开源软件"]
slug: "memcached"
draft: false
lastmod: "2011-07-22T08:48:35Z"
id: 1129876
url: "https://ninggy.iteye.com/blog/1129876"
---

最近初学了一下Memcached，网上有很多的前辈文章详细介绍过Memcached 的安装使用啊，我写着个的目的不是介绍Memcached，只是想把自己初次体验的过程记下来，以备那天真的需要了可以来此复习一下。

1.下载Memcached 地址：[http://code.google.com/p/memcached/downloads/list](http://code.google.com/p/memcached/downloads/list "http://code.google.com/p/memcached/downloads/list") 以及libevent地址：[http://www.monkey.org/~provos/libevent/](http://www.monkey.org/~provos/libevent/ "http://www.monkey.org/~provos/libevent/")

 

2.安装（我用的linux）

  1)先安装libevent。需要指定一个安装路径，即./configure –prefix=/usr；然后make；然后make install；  
  2)再安装memcached，需要指定libevent的安装路径即./configure –with-libevent=/usr；然后make；然后make install；

  3)测试安装是否成功：ls -al /usr/local/bin/mem*

 4)启动memcahced：/usr/local/bin/memcached -d -m 10 -u root -l 192.168.1.158 -p 12111 -c 256 -P /tmp/memcached.pid

 

3.下载Memcached的java客户端,客户端很多中，各种的差异网上有很多，我试了其中的三种：

  1.gwhalin-Memcached-Java-Client

     下载地址：[https://github.com/gwhalin/Memcached-Java-Client](https://github.com/gwhalin/Memcached-Java-Client)

  2.是有前辈在gwhatlin上改进的一个java客户端

     地址：[http://code.google.com/p/memcache-client-forjava/](http://code.google.com/p/memcache-client-forjava/ "http://code.google.com/p/memcache-client-forjava/")

    使用这个的时候的在可以在classlpath下用以个xml文件配置客户端信息。

   memcached.xml:

```
<?xml version="1.0" encoding="UTF-8"?>
<memcached>
    
    <client name="mclient0" compressEnable="true" defaultEncoding="UTF-8" socketpool="pool0">
        <errorHandler>com.alisoft.xplatform.asf.cache.memcached.MemcachedErrorHandler</errorHandler>
    </client>
      
    <socketpool name="pool0" failover="true" initConn="5" minConn="5" maxConn="250" maintSleep="0"
        nagle="false" socketTO="3000" aliveCheck="true">
        <servers>192.168.1.158:12111</servers>
    </socketpool>              
</memcached>
```

 

 3.是xmemcached

    地址：[http://code.google.com/p/xmemcached/downloads/list](http://code.google.com/p/xmemcached/downloads/list)

 

4.便写测试代码：

```
package com.strong;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;

import com.alisoft.xplatform.asf.cache.ICacheManager;
import com.alisoft.xplatform.asf.cache.IMemcachedCache;
import com.alisoft.xplatform.asf.cache.memcached.CacheUtil;
import com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;



public class MemcacheTest{
  
  static  ICacheManager<IMemcachedCache>  manager;
  static SockIOPool pool ;
  static MemcachedClient cache;
  
  @BeforeClass
  public static void setUpBeforeClass() throws Exception
  {
    manager = CacheUtil.getCacheManager(IMemcachedCache.class, MemcachedCacheManager.class.getName());
    manager.setConfigFile("memcached.xml");
    manager.setResponseStatInterval(5*1000);
    manager.start();
    
    pool = SockIOPool.getInstance();
    String[] server = { "192.168.1.158:12111" };
    pool.setServers(server);
    pool.setFailover(true);
    pool.setInitConn(10);
    pool.setMinConn(5);
    pool.setMaxConn(250);
    pool.setMaintSleep(30);
    pool.setNagle(false);
    pool.setSocketTO(3000);
    pool.setAliveCheck(true);
    pool.initialize();

    
    MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("192.168.1.158:12111"));
    cache = builder.build();
  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception
  {
    
    pool.shutDown();
    manager.stop();
    cache.shutdown();
  }
  
  @Test
  public void testXmemcached(){
    try { 
      cache.set("key1", 0, "232323");
      assertEquals("232323", cache.get("key1"));      
    } catch (TimeoutException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (MemcachedException e) {
      e.printStackTrace();
    }
  }
  
  @Test
  public void testQwhatLinMemcached(){

    MemCachedClient memCachedClient = new MemCachedClient(); 
    for(int i=0;i<10;i++){
      memCachedClient.set("test"+i, i+"testing");
    }
    
    for(int i=0;i<10;i++){      
      String result  = (String) memCachedClient.get("test"+i);
      assertEquals(i+"testing", result);
    }
  }
  
  @Test
  public void testWenChuMemcached(){

    IMemcachedCache cache = manager.getCache("mclient0");
    cache.remove("key1");
    cache.remove("key2");
    cache.remove("key3");
    
    cache.put("key1", "1");
    cache.put("key2", "222");//替换在添加
    
    cache.replace("key1", "333");
    
    cache.add("key3", "444");//只做添加
    cache.put("key2", "555");
      
    assertEquals("333", cache.get("key1"));
    assertEquals("555", cache.get("key2"));
    assertEquals("444", cache.get("key3"));
  }
}
```

 5.与spring的集成。网上有介绍和spring集成的实例，xmemcache在用户手册中专门介绍了与spring集成。详细的可以看它的官网：[http://code.google.com/p/xmemcached/wiki/User\_Guide\_zh](http://code.google.com/p/xmemcached/wiki/User_Guide_zh)