Memcached - 具体使用与工具类

【1】memcached.properties

//服务器信息
servers=127.0.0.1\:11211

【初始连接数、最小连接数、最大连接数、最大空闲时间】

initialConnections=10
minSpareConnections=5
maxSpareConnections=50
maxIdleTime=1800000

【最长租用时间】

其使用主要有两点,一是自查线程会检查正在被租用的连接,
如果发现已经被租用的时间超过这个值得,会将其从被租用的记录里剔除,并关闭这个连接;
另一个应用是上层进行MUTIL操作时,读取所有的数据的时间不能超过这个时间。

maxBusyTime=3000000

【连接池睡眠、超时、等待时间】


//设置连接池守护线程的睡眠时间
maintThreadSleep=5000

//Socket阻塞读取数据的超时时间
socketTimeOut=3000

//Socket阻塞建立连接的等待时间
socketConnectTO=3000


【nagleAlg:Socket的参数,如果是true在写数据时不缓冲,立即发送出去】

nagleAlg=false

【 hashingAlg】

 int hashingAlg = NATIVE_HASH – 池的hash bucket方式,主要是分为简单的hashCode取hash bucket数目的模
    和一致性哈希,前者在扩容时会造成命中率很大程度的下降,后者的好处是扩容时很大程度减少了缓存的重新
    分布

【2】MemcachedConn工具类

  • 初始化MemcachedConn;
package com.atguigu.springmvc.test;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

import java.io.IOException;

public class MemcachedConn
{
  private static String memcached_file = "/memcached.properties";

  private static String[] this_servers = { "192.168.4.188:11111" };

  private static int initialConnections = 10;

  private static int minSpareConnections = 5;

  private static int maxSpareConnections = 50;

  private static long maxIdleTime = 1800000L;

  private static long maxBusyTime = 300000L;

  private static long maintThreadSleep = 5000L;

  private static int socketTimeOut = 3000;

  private static int socketConnectTO = 3000;

  private static boolean nagleAlg = false;

  static String keyFlg = "";
  
	//获取SockIOPool 实例
  private static SockIOPool pool = SockIOPool.getInstance();

  static
  {
    try
    {
      ParseProperties parseProperties = ParseProperties.getInstance();
      parseProperties.setFilepath(memcached_file);

      if (parseProperties.getValueByKey("servers") != null) {
        String servers = parseProperties.getValueByKey("servers");

        if (servers.contains(";"))
          this_servers = servers.split(";");
        else {
          this_servers[0] = servers;
        }

      }

      if (parseProperties.getValueByKey("initialConnections") != null) {
        initialConnections = Integer.parseInt(parseProperties.getValueByKey("initialConnections"));
      }
      if (parseProperties.getValueByKey("minSpareConnections") != null) {
        minSpareConnections = Integer.parseInt(parseProperties.getValueByKey("minSpareConnections"));
      }
      if (parseProperties.getValueByKey("maxSpareConnections") != null) {
        maxSpareConnections = Integer.parseInt(parseProperties.getValueByKey("maxSpareConnections"));
      }
      if (parseProperties.getValueByKey("maxIdleTime") != null) {
        maxIdleTime = Integer.parseInt(parseProperties.getValueByKey("maxIdleTime"));
      }
      if (parseProperties.getValueByKey("maxBusyTime") != null) {
        maxBusyTime = Integer.parseInt(parseProperties.getValueByKey("maxBusyTime"));
      }
      if (parseProperties.getValueByKey("maintThreadSleep") != null) {
        maintThreadSleep = Integer.parseInt(parseProperties.getValueByKey("maintThreadSleep"));
      }
      if (parseProperties.getValueByKey("socketTimeOut") != null) {
        socketTimeOut = Integer.parseInt(parseProperties.getValueByKey("socketTimeOut"));
      }
      if (parseProperties.getValueByKey("socketConnectTO") != null) {
        socketConnectTO = Integer.parseInt(parseProperties.getValueByKey("socketConnectTO"));
      }
      if (parseProperties.getValueByKey("nagleAlg") != null) {
        if (parseProperties.getValueByKey("nagleAlg").equals("true"))
          nagleAlg = true;
        else {
          nagleAlg = false;
        }
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

  public static MemcachedConn getInstance()
  {
    conn();

    return new MemcachedConn();
  }
  /**
   * 单例模式--懒汉式
   * @return
   */
  public static MemCachedClient getMemCachedClient()
  {
    conn();

    MemCachedClient memCachedClient = new MemCachedClient();

    return memCachedClient;
  }
	//初始化pool,仅需要一次
  private static void conn()
  {
    pool.setServers(this_servers);
    
    //初始化时对每个服务器建立的连接数目
    pool.setInitConn(initialConnections);
    
	// 每个服务器建立最小的连接数,当自查线程发现与某个服务器建立连接数目小于这个数目时会弥补剩下的连接
    pool.setMinConn(minSpareConnections);
    /*每个服务器建立最大的连接数,当自查线程发现与某个服务器建立连接数目大于这个数目时就会逐个检查这些连接的空闲时间是否大于maxIdleTime,如果大于会关闭这些连接,直到连接数等于maxIdleTime*/
    pool.setMaxConn(maxSpareConnections);
    pool.setMaxIdle(maxIdleTime);
    pool.setMaxBusyTime(maxBusyTime);
    pool.setMaintSleep(maintThreadSleep);
    pool.setSocketTO(socketTimeOut);
    pool.setSocketConnectTO(socketConnectTO);
    pool.setNagle(nagleAlg);
    pool.setHashingAlg(2);
    //初始化是否完成的标志,只有初始化完成后上层才能正常使用池
    pool.initialize();
  }
}

【3】Memcached使用

  • 通过MemcachedConn使用memcached;
package com.atguigu.springmvc.test;

import com.danga.MemCached.MemCachedClient;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MemcachedHelper
{
  private static MemCachedClient memCachedClient = MemcachedConn.getMemCachedClient();

  public static MemcachedHelper getInstance()
  {
    return new MemcachedHelper();
  }

  public boolean add(String key, Object value)
  {
    return memCachedClient.add(MemcachedConn.keyFlg + key, value);
  }

  public boolean add(String key, Object value, Date expiry)
  {
    return memCachedClient.add(MemcachedConn.keyFlg + key, value, expiry);
  }

  public boolean add(String key, Object value, Integer flg)
  {
    return memCachedClient.add(MemcachedConn.keyFlg + key, value, flg);
  }

  public boolean update(String key, Object value)
  {
    return memCachedClient.replace(MemcachedConn.keyFlg + key, value);
  }

  public boolean update(String key, Object value, Date expiry)
  {
    return memCachedClient.replace(MemcachedConn.keyFlg + key, value, expiry);
  }

  public boolean update(String key, Object value, Integer flg)
  {
    return memCachedClient.replace(MemcachedConn.keyFlg + key, value, flg);
  }

  public boolean delete(String key)
  {
    return memCachedClient.delete(MemcachedConn.keyFlg + key);
  }

  public Object get(String key)
  {
    return memCachedClient.get(MemcachedConn.keyFlg + key);
  }

  public Object get(String key, Integer flg) {
    return memCachedClient.get(MemcachedConn.keyFlg + key, flg);
  }

  public List getAllKeys()
  {
    List list = new ArrayList();

    Map items = memCachedClient.statsItems();
    Iterator mapsIt;
    for (Iterator itemIt = items.keySet().iterator(); itemIt.hasNext(); 
      mapsIt.hasNext())
    {
      String itemKey = (String)itemIt.next();

      Map maps = (Map)items.get(itemKey);

      mapsIt = maps.keySet().iterator(); continue;
      String mapsKey = (String)mapsIt.next();
      String mapsValue = (String)maps.get(mapsKey);
	  //memcached key 类型  item_str:integer:str number
      if (mapsKey.endsWith("number")) {
        String[] arr = mapsKey.split(":");
        int slabNumber = Integer.valueOf(arr[1].trim()).intValue();
        int limit = Integer.valueOf(mapsValue.trim()).intValue();

        Map dumpMaps = memCachedClient.statsCacheDump(slabNumber, limit);
        Iterator allIt;
        for (Iterator dumpIt = dumpMaps.keySet().iterator(); dumpIt.hasNext(); 
          allIt.hasNext())
        {
          String dumpKey = (String)dumpIt.next();

          Map allMap = (Map)dumpMaps.get(dumpKey);
          allIt = allMap.keySet().iterator(); continue;
          String allKey = (String)allIt.next();
          list.add(allKey.trim());
        }

      }

    }

    return list;
  }

  public boolean existsKey(String key)
  {
    return memCachedClient.keyExists(MemcachedConn.keyFlg + key);
  }

  private void clearAll()
  {
    memCachedClient.flushAll();
  }
}

Linux下key的样式如下:

Memcached - 具体使用与工具类_第1张图片

你可能感兴趣的:(memcached,线程,服务器,Redis/Memcache)