作者:谢文友6123 | 来源:互联网 | 2017-10-10 18:58
关于memcached服务的安装可以参见:Ubuntu及Windows上安装memcached服务http://www.linuxidc.com/Linux/2012-08/69313.htm参考:http://www.linuxidc.com/Linux/2010-11/29573.htm废话少说直接上代码:先创建一个memcached的连接类,注意填写正确的memcached服
关于memcached服务的安装可以参见:Ubuntu及Windows上安装memcached服务 http://www.linuxidc.com/Linux/2012-08/69313.htm
参考:http://www.linuxidc.com/Linux/2010-11/29573.htm
废话少说直接上代码:
先创建一个memcached的连接类,注意填写正确的memcached服务器的IP及端口
- import java.io.IOException;
- import java.net.InetSocketAddress;
import java.util.concurrent.Future;
import net.spy.memcached.MemcachedClient;
public class MemClient {
private static MemcachedClient client = null;
static {
try {
client = new MemcachedClient(new InetSocketAddress("127.0.0.1",
11211));
System.out.println("CONNECTED TO SERVER");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public Future addToMemCache(String key, int timeOut, Object val) {
Future future = client.set(key, timeOut, val);
return future;
}
public Object getMemcachedValue(String key) {
return client.get(key);
}
}
再创建一个使用类,基本原理就是随机生成100对键值对存入,并检查是否全部存入,在设定的expire期限以后,读取看是否存入的数据都失效了
- import java.util.ArrayList;
- import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MemClientUser {
private static ArrayList keyStore = new ArrayList();
private static ArrayList> futures = new ArrayList>();
private static int counter = 0;
public static void main(String[] args) throws InterruptedException,
ExecutionException {
Logger.getLogger("net.spy.memcached").setLevel(Level.SEVERE);
final MemClient memClient = new MemClient();
for (int i = 0; i < 100; i++) {
final String key = getRandomKey();
final String value = getValueFromASource();
keyStore.add(key);
Future future = memClient.addToMemCache(key, 10, value);
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
if (future != null) {
futures.add(future);
counter++;
} else
System.out.println("future is null??");
}
System.out.println("VALUES TRIED: " + counter);
counter = 0;
for (final String key : keyStore) {
String val = (String) memClient.getMemcachedValue(key);
if (val != null)
counter++;
}
System.out.println("VALUES FOUND: " + counter);
Thread.sleep(10000);
counter = 0;
for (final String key : keyStore) {
String val = (String) memClient.getMemcachedValue(key);
if (val != null)
counter++;
}
System.out.println("VALUES REMAINING: " + counter);
}
private static String getRandomKey() {
return "RANDOM_KEY" + new Random().nextInt(99999);
}
private static String getValueFromASource() {
return "RANDOM_VALUE" + new Random().nextInt(99999);
}
}
测试结果如下: