Memcached(一)、HelloWorld

一、简介
高性能的架构离不开缓存,分布式缓存中的佼佼者当属memcached,它通过客户端将不同的key hash到不同的memcached服务器中,而获取的时候也到相同的服务器中获取,由于不需要做集群同步,也就省去了集群间同步的开销和延迟,所以它相对于ehcache等缓存来说能更好的支持分布式应用,具有更强的横向伸缩能力。
二、客户端
选择一个memcached客户端,我这里用的是memcached client for java(见附件),其他的还有Spymemcached,国产的有xmemcached,还有很多非java领域客户端。
三、HelloWorld
memcached.properties:
servers=localhost:11211
failover=true
initConn=10
minConn=5
maxConn=250
maintSleep=30
nagle=false
socketTO=3000
aliveCheck=true

单元测试类:
public class MemcachedMain {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
initPool();
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

@Before
public void setUp() throws Exception {

}

@After
public void tearDown() throws Exception {

}
private static void initPool() throws Exception{
Properties props = getProperties();
String[] servers = ((String)props.get("servers")).split(",");
// String[] servers = {"192.168.137.200:11211"};
SockIOPool pool = SockIOPool.getInstance();
pool.setServers(servers);
pool.setFailover(Boolean.valueOf((String)props.get("failover")));
pool.setInitConn(Integer.parseInt((String)props.get("initConn")));
pool.setMinConn(Integer.parseInt((String)props.get("minConn")));
pool.setMaxConn(Integer.parseInt((String)props.get("maxConn")));
pool.setMaintSleep(Integer.parseInt((String)props.get("maintSleep")));
pool.setNagle(Boolean.valueOf((String)props.get("magle")));
pool.setSocketTO(Integer.parseInt((String)props.get("socketTO")));
pool.setAliveCheck(Boolean.valueOf((String)props.get("aliveCheck")));
pool.initialize();
}
private static Properties getProperties() throws Exception{
Properties props = new Properties();
InputStream in = MemcachedMain.class.getResourceAsStream("/memcached.properties");
props.load(in);
return props;
}
@Test
public void memcachedHelloworld() throws Exception{
MemCachedClient client = new MemCachedClient();
for (int i = 0; i < 10; i++) {
boolean success = client.set("" + i, "Memcached Hello world!");
String result = (String) client.get("" + i);
System.out.println(String.format("get( %d ): %s", i, result));
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值