一、简介
高性能的架构离不开缓存,分布式缓存中的佼佼者当属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));
}
}
}