1、创建maven
项目,在pom.xml
文件中添加如下依赖项
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.2.0</version>
</dependency>
2、编写java 连接Hbase类:HBaseConfs.java
public class HBaseConfs {
private HBaseConfs(){}
private static Configuration getConf(){
Configuration conf=new Configuration();
conf.addResource(new Path("/opt/hbase/conf/hbase-site.xml"));
conf.addResource(new Path("/opt/hadoop/etc/hadoop/core-site.xml"));
return conf;
}
public static Connection getConn(){
Connection conn=null;
try {
conn= ConnectionFactory.createConnection(getConf());
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
public static Admin getAdmin(){
Admin admin=null;
try {
admin=getConn().getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
return admin;
}
}
3、编写建表实现类:CreateTable.java
public class CreateTable {
public static void main(String[] args){
Admin admin= HBaseConfs.getAdmin();
HTableDescriptor htd=new HTableDescriptor(TableName.valueOf(args[0]));
for (int i = 1; i < args.length; i++) {
try {
HColumnDescriptor family=new HColumnDescriptor(args[i]);
htd.addFamily(family);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
admin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4、打 jar 包,并上传到 Linux 虚拟机上执行
- path:jar在Linux上的路径
- cn.kgc:实现类所在的包名
hadoop jar /path/file.jar cn.kgc.CreateTable
5、实现插入方法类:InsertTable.java
执行第4步操作
public class InsertTable {
public static void main(String[] args) throws Exception {
Connection conn= HBaseConfs.getConn();
Admin admin=HBaseConfs.getAdmin();
TableName[] tableNames = admin.listTableNames();
for (TableName tableName : tableNames) {
System.out.println(tableName.getNameAsString());
}
Table table=conn.getTable(TableName.valueOf("customer"));
String[][] values={
{"1","A","a","1st White House","hhh"}
,{"2","B","b","10th aierlan","jjj"}
,{"3","C","c","111th dizhongha","kkk"}
,{"4","D","d","nowhere","LLL"}
};
for (int i = 0; i < values.length; i++) {
Put put=new Put(values[i][0].getBytes());
put.addColumn("name".getBytes(),"fname".getBytes(),values[i][1].getBytes());
put.addColumn("name".getBytes(),"lname".getBytes(),values[i][2].getBytes());
put.addColumn("addr".getBytes(),"address".getBytes(),values[i][3].getBytes());
put.addColumn("addr".getBytes(),"city".getBytes(),values[i][4].getBytes());
table.put(put);
}
admin.close();
conn.close();
}
}