memcached 的配置及 spymemcached 客户端简单使用

Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。同时也可以用作不同系统之间的数据共享。应用比较广泛。下面介绍一下环境的memcached环境的搭建及简单实用

  1. 1. 下载 libevent。官网下载 libevent
  2. 2. 下载 memcached。官网下载 memcached
  3. 3. 安装libevent,解压压缩包
       1:  ./configure –prefix=/usr/local/libevent
       2:  make
       3:  make install
  4. 4.安装memcached。
  5.    1:  ./configure-prefix=/usr/local/memcached-with-libevent –with-libevent=/usr/local/libevent
       2:  make
       3:  make install
  6. 5. 运行
  7.    1:  ./memcached -u root
  8. 不出意外的话,服务器端的安装完毕了。
  9. 简单的Java客户端Demo。使用的是spymemcached客户端
  10. 最近上生产环境因为使用memcached差点导致宕机。由于spymemcached在发不通主机是会不断的请求连接。同时代码的写法有问题,每一次请求都新建了一个客户端。所以需要注意的是,SpyMemcachedManager 应该全局使用一个对象。减少开销。
  11. /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package memcached;

    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.SocketAddress;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    import net.spy.memcached.AddrUtil;
    import net.spy.memcached.ConnectionObserver;
    import net.spy.memcached.MemcachedClient;
    import net.spy.memcached.transcoders.Transcoder;

    /**
    *
    * @author yingzi.zhu
    */
    public class SpyMemcachedManager {

        private List<String> servers;   // 192.168.159.129:11211
        private MemcachedClient memClient;
        public static int DEFAULT_TIMEOUT = 5;   
        public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS;
       
        public SpyMemcachedManager(List<String> servers) {       
            this.servers = servers;       
        }   
       
        public void connect() throws IOException {       
            if (memClient != null) {           
                return;           
            }       
            StringBuffer buf = new StringBuffer();       
            for (int i = 0; i < servers.size(); i++) {           
                String server = servers.get(i);           
                buf.append(server).append(" ");           
            }       
            memClient = new MemcachedClient(AddrUtil.getAddresses(buf.toString()));       
        }   
       
        public void disConnect() {       
            if (memClient == null) {           
                return;           
            }       
            memClient.shutdown();       
        }   
       
        public void addObserver(ConnectionObserver obs) {       
            memClient.addObserver(obs);       
        }   
       
        public void removeObserver(ConnectionObserver obs) {       
            memClient.removeObserver(obs);       
        }

       
        public boolean set(String key, Object value, int expire) {       
            Future<Boolean> f = memClient.set(key, expire, value);       
            return getBooleanValue(f);       
        }   
       
        public Object get(String key) {       
            return memClient.get(key);       
        }   
       
        public Object asyncGet(String key) {       
            Object obj = null;       
            Future<Object> f = memClient.asyncGet(key);       
            try {           
                obj = f.get(SpyMemcachedManager.DEFAULT_TIMEOUT,
                        SpyMemcachedManager.DEFAULT_TIMEUNIT);           
            } catch (Exception e) {           
                f.cancel(false);           
            }       
            return obj;       
        }   
       
        public boolean add(String key, Object value, int expire) {       
            Future<Boolean> f = memClient.add(key, expire, value);       
            return getBooleanValue(f);       
        }   
       
        public boolean replace(String key, Object value, int expire) {       
            Future<Boolean> f = memClient.replace(key, expire, value);       
            return getBooleanValue(f);       
        }   
       
        public boolean delete(String key) {       
            Future<Boolean> f = memClient.delete(key);       
            return getBooleanValue(f);       
        }   
       
        public boolean flush() {       
            Future<Boolean> f = memClient.flush();       
            return getBooleanValue(f);       
        }   
       
        public Map<String, Object> getMulti(Collection<String> keys) {       
            return memClient.getBulk(keys);       
        }   
       
        public Map<String, Object> getMulti(String[] keys) {       
            return memClient.getBulk(keys);       
        }   
       
        public Map<String, Object> asyncGetMulti(Collection<String> keys) {       
            Map map = null;       
            Future<Map<String, Object>> f = memClient.asyncGetBulk(keys);       
            try {           
                map = f.get(SpyMemcachedManager.DEFAULT_TIMEOUT,
                        SpyMemcachedManager.DEFAULT_TIMEUNIT);           
            } catch (Exception e) {           
                f.cancel(false);           
            }       
            return map;       
        }   
       
        public Map<String, Object> asyncGetMulti(String keys[]) {       
            Map map = null;       
            Future<Map<String, Object>> f = memClient.asyncGetBulk(keys);       
            try {           
                map = f.get(SpyMemcachedManager.DEFAULT_TIMEOUT,
                        SpyMemcachedManager.DEFAULT_TIMEUNIT);           
            } catch (Exception e) {           
                f.cancel(false);           
            }       
            return map;       
        }

        public long increment(String key, int by, long defaultValue, int expire) {       
            return memClient.incr(key, by, defaultValue, expire);       
        }   
       
        public long increment(String key, int by) {       
            return memClient.incr(key, by);       
        }   
       
        public long decrement(String key, int by, long defaultValue, int expire) {       
            return memClient.decr(key, by, defaultValue, expire);       
        }   
       
        public long decrement(String key, int by) {       
            return memClient.decr(key, by);       
        }   
       
        public long asyncIncrement(String key, int by) {       
            Future<Long> f = memClient.asyncIncr(key, by);       
            return getLongValue(f);       
        }   
       
        public long asyncDecrement(String key, int by) {       
            Future<Long> f = memClient.asyncDecr(key, by);       
            return getLongValue(f);       
        }
       
        public void printStats() throws IOException {       
            printStats(null);       
        }   
       
        public void printStats(OutputStream stream) throws IOException {       
            Map<SocketAddress, Map<String, String>> statMap =
                    memClient.getStats();       
            if (stream == null) {           
                stream = System.out;           
            }       
            StringBuffer buf = new StringBuffer();       
            Set<SocketAddress> addrSet = statMap.keySet();       
            Iterator<SocketAddress> iter = addrSet.iterator();       
            while (iter.hasNext()) {           
                SocketAddress addr = iter.next();           
                buf.append(addr.toString() + "/n");           
                Map<String, String> stat = statMap.get(addr);           
                Set<String> keys = stat.keySet();           
                Iterator<String> keyIter = keys.iterator();           
                while (keyIter.hasNext()) {               
                    String key = keyIter.next();               
                    String value = stat.get(key);               
                    buf.append("  key=" + key + ";value=" + value + "/n");               
                }           
                buf.append("/n");           
            }       
            stream.write(buf.toString().getBytes());       
            stream.flush();       
        }   
       
        public Transcoder getTranscoder() {       
            return memClient.getTranscoder();       
        }   
       
        private long getLongValue(Future<Long> f) {       
            try {           
                Long l = f.get(SpyMemcachedManager.DEFAULT_TIMEOUT,
                        SpyMemcachedManager.DEFAULT_TIMEUNIT);           
                return l.longValue();           
            } catch (Exception e) {           
                f.cancel(false);           
            }       
            return -1;       
        }   
       
        private boolean getBooleanValue(Future<Boolean> f) {       
            try {           
                Boolean bool = f.get(SpyMemcachedManager.DEFAULT_TIMEOUT,
                        SpyMemcachedManager.DEFAULT_TIMEUNIT);           
                return bool.booleanValue();           
            } catch (Exception e) {           
                f.cancel(false);           
                return false;           
            }       
        }   
    }
posted @ 2013-07-18 14:55  yingzi.zhu  阅读(5429)  评论(1编辑  收藏  举报