当前位置: 首页 > 工具软件 > jmemcached > 使用案例 >

spyMemcached与JMemcached

逄岳
2023-12-01
jMemcachedMemcached分布式缓存的java实现
SpyMemcachedMemcached的java客户端

1.启动jMemcached服务
int maxItems = 1024;
long maxBytes = 1024 * 2048;
long ceilingSize = 2048;
MemCacheDaemon daemon = new MemCacheDaemon();
daemon.setAddr(new InetSocketAddress("localhost", 11211));
LRUCacheStorageDelegate cacheStorage = new LRUCacheStorageDelegate(
maxItems, maxBytes, ceilingSize);

daemon.setCache(new Cache(cacheStorage));
daemon.setBinary(false);
daemon.start();

2.SpyMemcached操作jMemcached的方法
//客户端连接上缓存服务器
MemcachedClient c = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));

/*将key值,set到memcached中,过期时间(秒)*/  
public Future<Boolean> set(String key, int expiredTime, Object value) {
return c.set(key, expiredTime, value);
}

/*根据key值,过获取memcached中的值*/   
public <T> T get(String key) {
try {
return (T) c.get(key);
} catch (RuntimeException e) {
System.out.println("获取缓存出错");
System.out.println(e);
return null;
}
}

/*根据key值,删除memcached中的值*/   
public Future<Boolean> delete(String key) {
return c.delete(key);
}

/*根据key值,异步获取memcached中的值*/  
public <T> T asyncGet(String key) {

T t = null;
Future<Object> f = c.asyncGet(key);
try {
t = (T) f.get(5, TimeUnit.SECONDS);
} catch (Exception e) {
f.cancel(true);
}

return t;
}
 类似资料: