假設有4台機,IP及主機名如下:
192.168.100.105 c1 192.168.100.110 c2 192.168.100.115 c3 192.168.100.120 c4
調用HBase API的示例代碼:
String tableName = "User"; try { Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", "c1:2181,c2:2181,c3:2181,c4:2181"); Connection conn = ConnectionFactory.createConnection(conf); Admin admin = conn.getAdmin(); TableName tbObj = TableName.valueOf(tableName); if (admin.tableExists(tbObj)) { //debug運行一般會卡在這句 System.out.println(tableName + "表已存在!"); } else { HTableDescriptor desc = new HTableDescriptor(tbObj); admin.createTable(desc); System.out.println(tableName + "表創建成功!"); } } catch (Exception e) { System.out.println(e); }
原因:
ZooKeeper需要使用主機名訪問。
* 只能用主機名訪問。也就是說,即使把代碼中的主機名改成IP,也會卡死,例如:
conf.set("hbase.zookeeper.quorum", "192.168.100.105:2181,192.168.100.110:2181,192.168.100.115:2181,192.168.100.120:2181");
解決方法:
在運行代碼的主機的hosts文件添加主機名和IP的映射。
Linux
vim /etc/hosts
加入以下內容:
192.168.100.105 c1 192.168.100.110 c2 192.168.100.115 c3 192.168.100.120 c4
Windows
1.打開C:\Windows\System32\drivers\etc目錄
2.右鍵hosts文件屬性,去掉“只讀”屬性(就是不勾選)
3.安全 -> 編輯 -> User(一般還有括號用戶名)
4.在User的權限中,全部勾選為允許。
5.保存(確定 -> 確定 -> 確定)。
6.用記事本打開hosts文件,輸入以下內容:
192.168.100.105 c1 192.168.100.110 c2 192.168.100.115 c3 192.168.100.120 c4