在java程序中使用memcached

在完成“ memcached安装、运行”之后,来看看在java中怎么使用 memcached来提高web用户的性能,我这里使用的是阿里软件的同学开发一个缓存包alisoft-xplatform-asf-cache-2.5.2.jar(在 http://code.google.com/p/memcache-client-forjava/downloads/list 可以下载)。阿里软件同学开发的这个java版本的 memcached客户包,相当不错,其支持本地缓存,大提高了缓存对象的获取的效率。

创建以下工具类:MemCachedUtil

package cn.duoduo.module.cache;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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;

public class MemCachedUtil {

     
      private static final Logger                                    logger                              = Logger.getLogger(MemCachedUtil.class);
      //默认缓存3分钟
      private static final int                                          REF_SECONDS          = 3 * 60;
     
      private static ICacheManager<IMemcachedCache> manager;
     
      private static Map<String, IMemcachedCache>    cacheArray;
     
      private static final String                                    defalutCacheName = "mclient1";
     
      static {
              cacheArray = new HashMap<String, IMemcachedCache>();
              manager = CacheUtil.getCacheManager(IMemcachedCache.class, MemcachedCacheManager.class
                      .getName());
              // manager.setConfigFile("memcached.xml");
              manager.start();
              cacheArray.put(defalutCacheName, manager.getCache(defalutCacheName));
      }

      private static String getCacheName(String type, Object key) {
              StringBuffer cacheName = new StringBuffer(type);
              if (key != null) {
                      cacheName.append("_").append(key);
              }
              return cacheName.toString();
      }
     
      public static void set(String type, Object key, Object value) {
              set(type, key, value, REF_SECONDS);
      }
     
      public static void putNoTimeInCache(String type, Object key, Object value) {
              if (value != null) {
                      set(type, key, value, -1);
              }
      }

      public static void set(String type, Object key, Object value, int seconds) {
              if (value != null) {
                      String cacheName = getCacheName(type, key);
                      try {
                              if (seconds < 1) {
                                      cacheArray.get(defalutCacheName).put(cacheName, value);
                              } else {
                                      cacheArray.get(defalutCacheName).put(cacheName, value, seconds);
                              }
                      } catch (Exception e) {
                              logger.log(Level.INFO, "cache " + defalutCacheName + " socket error。");
                      }
              }
      }
     
      public static void delete(String type, Object key) {
              cacheArray.get(defalutCacheName).remove(getCacheName(type, key));
      }
     
      @SuppressWarnings("unchecked")
      public static <T> T get(Class<T> clazz, String type, Object key) {
              return (T) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
      }
     
      @SuppressWarnings("unchecked")
      public static <T> List<T> getList(Class<T> clazz, String type, Object key) {
              return (List<T>) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
      }
     
      @SuppressWarnings("unchecked")
      public static <T> T get(Class<T> clazz, String type, Object key, int localTTL) {
              try {
                      return (T) cacheArray.get(defalutCacheName).get(getCacheName(type, key), localTTL);
              } catch (Exception e) {
                      return null;
              }
      }
     
      @SuppressWarnings("unchecked")
      public static <T> List<T> getList(Class<T> clazz, String type, Object key, int localTTL) {
              try {
                      return (List<T>) cacheArray.get(defalutCacheName)
                              .get(getCacheName(type, key), localTTL);
              } catch (Exception e) {
                      return null;
              }
      }
     
      @SuppressWarnings("unchecked")
      public static <V> Map<String, V> getMap(Class<V> clazz, String type, Object key, int localTTL) {
              try {
                      return (Map<String, V>) cacheArray.get(defalutCacheName).get(getCacheName(type, key),
                              localTTL);
              } catch (Exception e) {
                      return null;
              }
      }
     
      @SuppressWarnings("unchecked")
      public static <V> Map<String, V> getMap(Class<V> clazz, String type, Object key) {
              try {
                      return (Map<String, V>) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
              } catch (Exception e) {
                      return null;
              }
      }
     
      public static Set<String> getKeyList() {
              return cacheArray.get(defalutCacheName).keySet();
      }
     
      public static void clear() {
              cacheArray.get(defalutCacheName).clear();
      }

      public static void close() {
              manager.stop();
      }

      public static void main(String argv[]) {
              if (argv.length == 0) {
                      System.out.println("Usage:MemCachedUtil get|del|set|list [type] [key] [value]");
                      return;
              }
              String type = null;
              String key = null;
              String value = null;
              if ("get".equals(argv[0])) {
                      if (argv.length < 3) {
                              System.out.println("Usage:MemCachedUtil get type key");
                              return;
                      }
                      type = argv[1];
                      key = argv[2];
                      System.out.println(MemCachedUtil.get(Object.class, type, key));
              } else if ("del".equals(argv[0])) {
                      if (argv.length < 3) {
                              System.out.println("Usage:MemCachedUtil del type key");
                              return;
                      }
                      type = argv[1];
                      key = argv[2];
                      MemCachedUtil.delete(type, key);
              } else if ("set".equals(argv[0])) {
                      if (argv.length < 4) {
                              System.out.println("Usage:MemCachedUtil set type key value");
                              return;
                      }
                      type = argv[1];
                      key = argv[2];
                      value = argv[3];
                      MemCachedUtil.set(type, key, value);
              } else if ("list".equals(argv[0])) {
                      System.out.println(MemCachedUtil.getKeyList());
              }
              MemCachedUtil.close();
      }
}

工具类写好了,不过它还需要一个配置文件memcached.xml:
<?xml version="1.0" encoding="UTF-8"?>
<memcached>
      <client name="mclient1" compressEnable="true" defaultEncoding="UTF-8" socketpool="pool1">
    <errorHandler>com.alisoft.xplatform.asf.cache.memcached.MemcachedErrorHandler</errorHandler>
      </client>
      <socketpool name="pool1" failover="true" initConn="10" minConn="50" maxConn="1024" maintSleep="0"
            nagle="false" socketTO="3000" aliveCheck="true">
            <servers>192.168.1.105:11211</servers>
      </socketpool>
</memcached>

好了,正确引入必要的依赖包后,就可以运行了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值