刚成功跑通了xmemcached + 3节点memcached 试验,记录一下试验过程:
----环境:
VMWare跑了3台Ubuntu,ip分别是192.168.66.91 192.168.66.92 192.168.66.93
3台ubuntu都装了memcached
eclipse装在192.168.66.91上,用于跑xmemcached
----过程:
首先,memcached的安装、启动和验证就不说了,按照虎皇的ppt来就行。
要注意的是,memcached正常跑起来后,需要在每一台机器上执行下面这行命令,别的机器才能访问当前机器的memcached:
memcached -l 192.168.66.xx:11211 -u root -d
该命令的作用是绑定当前机器的对外ip,否则只能本机用127.0.0.1访问。
其次,在eclipse中建立Java工程,并引入下面几个包:
然后执行以下代码:
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;
public class MemcachedClientTest {
public static void main(String[] args) {
//指定三台跑memcached的服务器
MemcachedClientBuilder builder = new XMemcachedClientBuilder(
AddrUtil.getAddresses("192.168.66.91:11211 192.168.66.92:11211 192.168.66.93:11211"),
new int[] {1,1,1});
// 设置连接池大小,即客户端个数
builder.setConnectionPoolSize(50);
// 宕机报警
builder.setFailureMode(true);
// 使用二进制文件
builder.setCommandFactory(new BinaryCommandFactory());
MemcachedClient memcachedClient = null;
try {
memcachedClient = builder.build();
try {
// 设置/获取
memcachedClient.set("zlex", 36000, "set/get");
System.out.println(memcachedClient.get("zlex"));
//试验一次性哈希,以下两条数据将分步到与存zlex不同的节点
memcachedClient.set("lion", 36000, "comeon");
memcachedClient.set("leon", 36000, "hello");
// 替换
memcachedClient.replace("zlex", 36000, "replace");
System.out.println(memcachedClient.get("zlex"));
// 移除
memcachedClient.delete("zlex");
memcachedClient.delete("lion");
memcachedClient.delete("leon");
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MemcachedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (memcachedClient != null) {
try {
memcachedClient.shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
单步调试会发现插入的3条数据分布在了两台服务器上,zlex和leon在同一台服务器,应该是zlex和leon的哈希值落在了同一区间:
Xmemcached + 3节点Memcached 试验
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:http://www.heiqu.com/b5e25e7786e3bbe530f97b1f15255ac4.html