在此之前请确保Hadoop和Hbase正确安装及启动,如果不是请移步到安装和配置Hbase相关文章中。本文解决服务器启动成功,并且Hbase shell创建表插入记录没问题,就是本地写java代码时连不上卡住并且不报错和抛出异常。
第一步:查看服务器的主机名(以windows为例,linux例子很多):
然后在你开发代码的环境中,C:\Windows\System32\drivers\etc目录找到host文件,添加
192.168.1.147 mycomputer
服务器的ip和主机名
然后运行代码
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/**
* HBase操作工具类:Java工具类建议采用单例模式封装
* 启动hbase
* list查看表
* Hbase表的设计 创建时不需要指定列
* 先创建表
* create 'imooc_course_clickcount','info'
*/
public class HBaseUtils {
HBaseAdmin admin = null;
Configuration configuration = null;
/**
* 私有改造方法
* hbase安装目录conf下hbase-site.xml的配置信息
*/
private HBaseUtils(){
configuration = new Configuration();
configuration.set("hbase.zookeeper.quorum", "192.168.1.147:2181");
configuration.set("hbase.rootdir", "hdfs://192.168.1.147/hbase");
try {
admin = new HBaseAdmin(configuration);
} catch (IOException e) {
e.printStackTrace();
}
}
private static HBaseUtils instance = null;
public static synchronized HBaseUtils getInstance() {
if(null == instance) {
instance = new HBaseUtils();
}
return instance;
}
/**
* 根据表名获取到HTable实例
*/
public HTable getTable(String tableName) {
HTable table = null;
try {
table = new HTable(configuration, tableName);
} catch (IOException e) {
e.printStackTrace();
}
return table;
}
/**
* 添加一条记录到HBase表
* @param tableName HBase表名
* @param rowkey HBase表的rowkey
* @param cf HBase表的columnfamily
* @param column HBase表的列
* @param value 写入HBase表的值
*/
public void put(String tableName, String rowkey, String cf, String column, String value) {
HTable table = getTable(tableName);
Put put = new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(cf), Bytes.toBytes(column), Bytes.toBytes(value));
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//这是测试
// HTable table = HBaseUtils.getInstance().getTable("imooc_course_clickcount");
// System.out.println(table.getName().getNameAsString());
String tableName = "imooc_course_clickcount" ;
String rowkey = "20171111_88";
String cf = "info" ;
String column = "click_count";
String value = "2";
HBaseUtils.getInstance().put(tableName, rowkey, cf, column, value);
System.out.println("插入一条数据");
}
}