您的位置:首页 > 数据库 > Memcache

memcached CS 用法

2011-05-23 17:21 113 查看
Memcached

顾名思义,就是用内存做数据缓存,

这个概念有许多的实现项目,

我也是学习到白衣大侠的springside3中的用法,

现学现卖吧

此处演示c/s 模式的用法,其实在web应用上可以使用memcached做为EHcache的替代.

服务器

jmemcached-core-1.0.0.jar

客户端memcached-2.6.jar

先是服务器:

package memcached;
import java.util.ArrayList;
import java.util.List;
import net.spy.memcached.AddrUtil;
import com.thimbleware.jmemcached.CacheImpl;
import com.thimbleware.jmemcached.MemCacheDaemon;
import com.thimbleware.jmemcached.storage.hash.ConcurrentLinkedHashMap;
import java.io.*;
public class TestServier {
private static MemCacheDaemon jmemcached=null;
private final static int maxItems=1024;
private final static long maxBytes=1024*1024*2;
private final static int ceilingSize=1024;
private final static boolean binary=false;
private final static int idleTime=60*60*1;
private final static String addr="localhost:11211";
/**

* @param args
*/
public static void main(String[] args) {
ConcurrentLinkedHashMap cacheStorage=ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.LRU, maxItems, maxBytes);

jmemcached=new MemCacheDaemon();
jmemcached.setCache(new CacheImpl(cacheStorage));
jmemcached.setBinary(binary);
jmemcached.setIdleTime(idleTime);

jmemcached.setAddr(AddrUtil.getAddresses(addr).get(0));
jmemcached.start();

String str="";
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(str!="exit"){
try {
str=br.readLine();

}
catch (IOException e) {

}
}

}
}


客户端代码

package memcached;
import java.io.IOException;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Locator;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.FailureMode;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
public class IntroTester {
/**
*
* @param args
*/
public static void main(String[] args) {

try {

//链接工厂创建器
ConnectionFactoryBuilder cfb=new ConnectionFactoryBuilder();
cfb.setFailureMode(FailureMode.Redistribute);
cfb.setDaemon(true);
cfb.setProtocol(Protocol.TEXT);

cfb.setLocatorType(Locator.CONSISTENT);
cfb.setHashAlg(HashAlgorithm.KETAMA_HASH);

cfb.setOpTimeout(1000);

//新建客户端
MemcachedClient client=new MemcachedClient(cfb.build(),AddrUtil.getAddresses("127.0.0.1:11211"));

//存放一个对象
client.add("name", 60*60*1, "Allchin");

String str=client.get("name").toString();

System.out.println(str);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: