MemCached缓存

在服务器端安装了MemCached服务过后我们就可以使用第三方缓存技术MemCached,这个使用比较简单,

在系统初始化的时候就可以加载缓存

public class CacheService {
 boolean cacheUse;

 // 指定memcached服务地址
 String[] cacheServerList;

 // 设置初始连接数100
 int initialConnections = 100;
 // 最小连接数 5
 int minSpareConnections = 5;
 // 最大连接数 50
 int maxSpareConnections = 50;
 // 设置一个连接最大空闲时间30分钟
 long maxIdleTime = 1000 * 60 * 30;
 // 设置主线程睡眠时间 5分钟
 long maxBusyTime = 1000 * 60 * 5;
 // 每隔5秒醒来
 long maintThreadSleep = 1000 * 5;
 // 设置 读取 超时10秒钟
 int socketTimeOut = 1000 * 10;
 // 不设置连接超时
 int socketConnectTO = 0;
 // 关闭nagle算法
 boolean nagleAlg = false;
 // pool

 MemCachedClient mc;

 public CacheService() {

 }

 public String[] getCacheServerList() {
  return cacheServerList;
 }

 public void setCacheServerList(String[] cacheServerList) {
  this.cacheServerList = cacheServerList;
 }

 public boolean isCacheUse() {
  return cacheUse;
 }

 public void setCacheUse(boolean cacheUse) {
  this.cacheUse = cacheUse;
 }

 /**
  * 放入
  *
  */
 public void put(String key, Object obj) {
  Assert.hasText(key);
  Assert.notNull(obj);
  mc.set(key, obj);
 }

 /**
  * 放入 EXPIRY=10000 >> 10秒,小于10秒则说明永不过期 EXPIRY=3600000 >> 60分钟 new
  * Date(3600000)
  */
 public void put(String key, Object obj, Date expiry) {
  Assert.hasText(key);
  Assert.notNull(obj);
  mc.set(key, obj, expiry);
 }

 /**
  * 删除
  */
 public void remove(String key) {
  Assert.hasText(key);
  mc.delete(key);
 }

 /**
  * 得到
  */
 public Object get(String key) {
  Assert.hasText(key);
  return mc.get(key);
 }

 /**
  * 得到
  */
 public Map<String, Object> get(String[] keys) {
  // Assert.notEmpty(keys);
  return mc.getMulti(keys);
 }

 /**
  * 判断是否存在
  *
  */
 public boolean exist(String key) {
  Assert.hasText(key);
  return mc.keyExists(key);
 }

 /**
  * 清理所有数据缓存
  */
 public void clear() {
  mc.flushAll();
 }

 /**
  * 系统启动的时候初始化cache
  */

 public void init() throws Exception {
  if (cacheUse == true) {
   try {
    SockIOPool pool = SockIOPool.getInstance();
    pool.setServers(cacheServerList);
    pool.setInitConn(initialConnections);
    pool.setMinConn(minSpareConnections);
    pool.setMaxConn(maxSpareConnections);
    pool.setMaxIdle(maxIdleTime);
    pool.setMaxBusyTime(maxBusyTime);
    pool.setMaintSleep(maintThreadSleep);
    pool.setSocketTO(socketTimeOut);
    pool.setSocketConnectTO(socketConnectTO);
    pool.setNagle(nagleAlg);
    pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);
    // 开始初始化 连接池
    pool.initialize();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  mc = new MemCachedClient();
 }

}

在properties中配置,在spring启动的时候加载,就会调用该缓存。

cache.properties:

##是否使用缓存服务器
cache.use=true
##缓存服务器IP
cache.memecahed.ip=127.0.0.1:11211

猜你喜欢

转载自blog.csdn.net/scjava/article/details/84167999