CacheUtil - Memcached全局工具类
- - 企业架构 - ITeye博客* 如果key不存在,存进去 true. 已有 0 人发表留言,猛击->> 这里<<-参与讨论. —软件人才免语言低担保 赴美带薪读研.
1、memCache.properties:
memcache=192.168.3.230\:11211 time=7200
package com.common.common;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.cdoframework.cdolib.data.cdo.CDO;
import net.spy.memcached.MemcachedClient;
/**
* cache的失效时间,0或者负数为永久有效
* 如果超过60*60*24*30为从1970年以来的时间数,否则为从现在起的时间数
* @author Administrator
*
*/
public class CacheUtil {
public static int DEFAULT_TIMEOUT = 1;
public static TimeUnit DEFAULT_TIMEUNIT = TimeUnit.SECONDS;
private static MemcachedClient memCachedClient;
static{
try {
//memCachedClient = new MemcachedClient();
String hosts = ProPertiesUtil.getValue("/memCache.properties", "memcache");
String[] servers = hosts.split(";");
List<InetSocketAddress> lsinetSocketAddress = new ArrayList<InetSocketAddress>();
for(int i=0;i<servers.length;i++){
String[] hp = servers[i].split(":");
lsinetSocketAddress.add(new InetSocketAddress(hp[0],Integer.parseInt(hp[1])));
}
memCachedClient = new MemcachedClient(lsinetSocketAddress);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 覆盖此key值
* @param key
* @param object
* @param time
* @return
*/
public static boolean put(String key,Object object,int time){
Future<Boolean> f = memCachedClient.set(key, time, object);
return getBooleanValue(f);
}
/**
* 如果key不存在,存进去 true
* 如果存在,false
* @param key
* @param object
* @param time
* @return
*/
public static boolean putNotExist(String key,Object object,int time){
Future<Boolean> f = memCachedClient.add(key, time, object);
return getBooleanValue(f);
}
/**
* 获得
* @param key
* @return
*/
public static Object get(String key){
return memCachedClient.get(key);
}
/**
* 删除
* @param key
* @return
*/
public static boolean delete(String key) {
Future<Boolean> f = memCachedClient.delete(key);
return getBooleanValue(f);
}
/**
* 清除cache
* @return
*/
public boolean flush() {
Future<Boolean> f = memCachedClient.flush();
return getBooleanValue(f);
}
private static boolean getBooleanValue(Future<Boolean> f) {
try {
Boolean bool = f.get(DEFAULT_TIMEOUT,DEFAULT_TIMEUNIT);
return bool.booleanValue();
} catch (Exception e) {
f.cancel(false);
return false;
}
}
public static void main(String[] args) {
System.out.println(CacheUtil.get("1more_award_5_33" ));
}
}
使用:
Object object = CacheUtil.get("global_access_token");
if(object == null){
access_token = HttpsUtil.getTokenFromWX();
CacheUtil.put("global_access_token", access_token, 7180);
}
..