1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| package hbase_hdfs;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.client.TableDescriptorBuilder; import org.apache.hadoop.hbase.util.Bytes;
public class CreatTable {
public static Configuration configuration; public static Admin admin; public static Connection connection; public static void main(String[] args) throws IOException { init(); creatTable("WordCount",new String[] {"word"}); insertData("WordCount", "1", "word", "1", "hadoop,hbase,zookeeper"); insertData("WordCount", "2", "word", "2", "hello,hbase,world"); insertData("WordCount", "3", "word", "3", "hello,hadoop,world"); insertData("WordCount", "4", "word", "4", "hello,zookeeper,world"); close(); } public static void init() throws IOException { configuration = HBaseConfiguration.create(); configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase"); connection = ConnectionFactory.createConnection(configuration); admin = connection.getAdmin(); System.out.println("连接成功"); }
public static void close() { if(admin!=null) { admin.close(); } if(connection!=null) { try { connection.close(); } catch (IOException e) {
e.printStackTrace(); } } } public static void creatTable(String myTableName,String[] colFamily) throws IOException { TableName tableName = TableName.valueOf(myTableName); if(admin.tableExists(tableName)) { System.out.println("该表已存在,正在删除"); admin. disableTableAsync(TableName.valueOf(myTableName)); admin.deleteTable(TableName.valueOf(myTableName)); } TableDescriptorBuilder tableDescriptor = TableDescriptorBuilder.newBuilder(tableName); for(String str:colFamily) { ColumnFamilyDescriptor family = ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(str)).build(); tableDescriptor.setColumnFamily(family); admin.createTable(tableDescriptor.build()); } } public static void insertData(String tableName,String rowKey,String colFamily,String col,String val) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Put put = new Put(rowKey.getBytes()); put.addColumn(colFamily.getBytes(),col.getBytes(), val.getBytes()); table.put(put); table.close(); System.out.println("插入成功"); } }
|