Hbase-HbaseAPI(一)编写HbaseAPI

Posted on 2020-04-24 15:57  MissRong  阅读(446)  评论(0)    收藏  举报

HBase-JavaAPI

一、新建Maven Project

新建项目后在pom.xml中添加依赖(在原有Hadoop、Zookeeper依赖的基础上):

<dependency>

<groupId>org.apache.hbase</groupId>

<artifactId>hbase-server</artifactId>

<version>1.3.1</version>

</dependency>

 

<dependency>

<groupId>org.apache.hbase</groupId>

<artifactId>hbase-client</artifactId>

<version>1.3.1</version>

</dependency>

 

或者自己搜Maven-->进入官网后再搜Hbase-->下载...Client和...Server都找1.3.1的版本--》复制粘贴对应的依赖。

二、编写HBaseAPI

注意,这部分的学习内容,这里先学习使用老版本的API,接着再写出新版本的API调用方式。

因为在企业中,有些时候我们需要一些过时的API来提供更好的兼容性。

1) 首先需要获取Configuration对象:

1 public static Configuration conf;
2 static{
3     //使用HBaseConfiguration的单例方法实例化
4     conf = HBaseConfiguration.create();
5     conf.set("hbase.zookeeper.quorum", "bigdata111");
6     conf.set("hbase.zookeeper.property.clientPort", "2181");
7     conf.set("zookeeper.znode.parent", "/hbase");
8 }

hbase.zookeeper.quorum 这个值查找方法:

[root@bigdata111 ~]# cd /opt/module/hbase-1.3.1/

[root@bigdata111 hbase-1.3.1]# vi conf/hbase-site.xml

 

 2) 判断表是否存在:

1 public static boolean isTableExist(String tableName) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
2     //在HBase中管理、访问表需要先创建HBaseAdmin对象
3     Connection connection = ConnectionFactory.createConnection(conf);
4     HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
5     //或者:HBaseAdmin admin = new HBaseAdmin(conf);
6     return admin.tableExists(tableName);
7 }

3) 创建表

 1 public static void createTable(String tableName, String... columnFamily) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
 2     HBaseAdmin admin = new HBaseAdmin(conf);
 3     //判断表是否存在
 4     if(isTableExist(tableName)){
 5     System.out.println("表" + tableName + "已存在");
 6     //System.exit(0);
 7     }else{
 8         //创建表属性对象,表名需要转字节
 9         HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
10         //创建多个列族
11         for(String cf : columnFamily){
12         descriptor.addFamily(new HColumnDescriptor(cf));
13         }
14     //根据对表的配置,创建表
15     admin.createTable(descriptor);
16     System.out.println("表" + tableName + "创建成功!");
17     }
18 }

4) 删除表

 1 public static void dropTable(String tableName) throws Exception{
 2     HBaseAdmin admin = new HBaseAdmin(conf);
 3     if(isTableExist(tableName)){
 4         admin.disableTable(tableName);
 5         admin.deleteTable(tableName);
 6         System.out.println("表" + tableName + "删除成功!");
 7     }else{
 8         System.out.println("表" + tableName + "不存在!");
 9     }
10 }

5) 向表中插入数据

 1 public static void addRowData(String tableName, String rowKey, String columnFamily, String column, String value) throws Exception{
 2     //创建HTable对象
 3     HTable hTable = new HTable(conf, tableName);
 4     //向表中插入数据
 5     Put put = new Put(Bytes.toBytes(rowKey));
 6     //向Put对象中组装数据
 7     put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(value));
 8     hTable.put(put);
 9     hTable.close();
10     System.out.println("插入数据成功");
11 }

6) 删除多行数据

 1 public static void deleteMultiRow(String tableName, String... rows) throws IOException{
 2     HTable hTable = new HTable(conf, tableName);
 3     List<Delete> deleteList = new ArrayList<Delete>();
 4     for(String row : rows){
 5         Delete delete = new Delete(Bytes.toBytes(row));
 6         deleteList.add(delete);
 7     }
 8     hTable.delete(deleteList);
 9     hTable.close();
10 }

接下来执行删除多行方法:

1 deleteMultiRow("city","1001","1003");

 

7) 得到所有数据

 1 public static void getAllRows(String tableName) throws IOException{
 2     HTable hTable = new HTable(conf, tableName);
 3     //得到用于扫描region的对象
 4     Scan scan = new Scan();
 5     //使用HTable得到resultcanner实现类的对象
 6     ResultScanner resultScanner = hTable.getScanner(scan);
 7     for(Result result : resultScanner){
 8         Cell[] cells = result.rawCells();
 9         for(Cell cell : cells){
10             //得到rowkey
11             System.out.println("行键:" + Bytes.toString(CellUtil.cloneRow(cell)));
12             //得到列族
13             System.out.println("列族" + Bytes.toString(CellUtil.cloneFamily(cell)));
14             System.out.println("列:" + Bytes.toString(CellUtil.cloneQualifier(cell)));
15             System.out.println("值:" + Bytes.toString(CellUtil.cloneValue(cell)));
16         }
17     }
18 }

8) 得到某一行键所在所有数据

 1 public static void getRow(String tableName,String rowKey) throws IOException {
 2         //1.创建一个HTable对象
 3         HTable hTable = new HTable(conf,tableName);
 4         //2.创建Get对象
 5         Get get = new Get(Bytes.toBytes(rowKey));
 6         //get.setMaxVersions();显示所有版本
 7         //get.setTimeStamp();显示指定时间戳的版本
 8         //3.使用HTable得到result实现类的对象
 9         Result result = hTable.get(get);
10         //4.对于每行得到各个列的值
11         for(Cell cell:result.rawCells()){
12             System.out.println("行键:"+Bytes.toString(CellUtil.cloneRow(cell))+"\t"+
13                     "列簇:"+Bytes.toString(CellUtil.cloneFamily(cell))+"\t"+
14                     "列名:"+Bytes.toString(CellUtil.cloneQualifier(cell))+"\t"+
15                     "数据:"+Bytes.toString(CellUtil.cloneValue(cell))+"\t"+
16                     "时间戳:"+cell.getTimestamp());
17         }
18     }

执行操作

1 getRow("city","1002");

结果:

行键:1002 列簇:cf 列名:countries 数据:TUS 时间戳:1587539063951

行键:1002 列簇:cf 列名:name 数据:New York 时间戳:1587539063951

9) 获取某一行指定“列族:列”的数据

 1 public static void getRowCol(String tableName,String rowKey,String colFamily,String col) throws IOException {
 2         //1.创建HTable对象
 3         HTable hTable = new HTable(conf, tableName);
 4         //2.创建Get对象
 5         Get get = new Get(Bytes.toBytes(rowKey));
 6         //3.将要查询的列簇、列名传入get
 7         get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
 8         //4.使用HTable得到result实现类的对象
 9         Result result = hTable.get(get);
10         for(Cell cell:result.rawCells()){
11             System.out.println("行键:"+Bytes.toString(result.getRow())+"\t"+
12                     "列簇:"+Bytes.toString(CellUtil.cloneFamily(cell))+"\t"+
13                     "列名:"+Bytes.toString(CellUtil.cloneQualifier(cell))+"\t"+
14                     "数据:"+Bytes.toString(CellUtil.cloneValue(cell)));
15         }
16     }

查询操作:

getRowCol("city","1002","cf","countries");

执行结果:

行键:1002 列簇:cf 列名:countries 数据:TUS

三、自写HBase-JavaAPI代码完整展示

  1 package hbase;
  2 
  3 import org.apache.hadoop.conf.Configuration;
  4 import org.apache.hadoop.hbase.*;
  5 import org.apache.hadoop.hbase.client.*;
  6 import org.apache.hadoop.hbase.util.Bytes;
  7 
  8 import java.io.IOException;
  9 import java.util.ArrayList;
 10 import java.util.List;
 11 
 12 /**
 13  * Author : ASUS and xinrong
 14  * Version : 2020/4/21 & 1.0
 15  */
 16 public class HBASE_API {
 17     /**
 18      * 首先要获取Configuration对象,获取配置文件
 19      */
 20     private static Configuration conf = null;
 21     /**
 22      * 初始化
 23      */
 24      static{
 25          //1.使用HbaseConfiguration 获取conf
 26         conf = HBaseConfiguration.create();
 27         //2.连接Zookeeper集群
 28         //注意,使用主机名之前要确保Windows配置文件hosts中配置上Linux对应的ip和主机名的映射。
 29         //随意写一个Hbase主机名即可,比如我这里写的就是bigdata111
 30         conf.set("hbase.zookeeper.quorum", "bigdata111");
 31         conf.set("hbase.zookeeper.property.clientPort","2181");
 32         conf.set("zookeeper.znode.parent", "/hbase");
 33     }
 34 
 35     /**
 36      * 一、判断表是否存在
 37      * @param tableName
 38      * @return
 39      * @throws IOException
 40      */
 41     public static boolean is_table_exists(String tableName) throws IOException {
 42 //         //1.创建Hbase客户端
 43 //        Connection connection = ConnectionFactory.createConnection(conf);
 44 //        HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
 45         //1.在HBase中管理、访问表需要先创建HBaseAdmin对象
 46         HBaseAdmin admin = new HBaseAdmin(conf);
 47         //2.判断表是否存在
 48         return admin.tableExists(Bytes.toBytes(tableName));
 49         // return admin.tableExists(tableName); 不转换也可
 50     }
 51 
 52     /**
 53      * 二、创建一个表
 54      * @param tableName
 55      * @param columeFamily 动态创建列簇
 56      * @throws IOException
 57      */
 58     public static void createTable(String tableName,String... columeFamily) throws IOException {
 59         //1.创建Hbase客户端
 60         Connection connection = ConnectionFactory.createConnection(conf);
 61         //在HBase中管理、访问表需要先创建HBaseAdmin对象
 62         HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();
 63         //2.判断表是否存在
 64         if(is_table_exists(tableName)){
 65             System.out.println(tableName+"已存在!");
 66         }else{
 67             //1.先创建表的描述对象
 68             HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
 69             //2.创建列簇
 70             for(String cf:columeFamily){
 71                 hTableDescriptor.addFamily(new HColumnDescriptor(cf));
 72             }
 73             admin.createTable(hTableDescriptor);
 74             System.out.println(tableName+"表已创建成功!");
 75         }
 76     }
 77 
 78     /**
 79      * 三、插入数据(一次只能插入一条)
 80      * @param nameTable
 81      * @param rowKey  行键
 82      * @param columeFamily  列簇
 83      * @param col  列名
 84      * @param value  数据
 85      * @throws IOException
 86      */
 87     public static void putTable(String nameTable,String rowKey,
 88                                 String columeFamily,String col,String value) throws IOException {
 89         //1.创建一个HTable对象
 90         HTable hTable = new HTable(conf, nameTable);
 91         //2.创建Put对象
 92         Put put = new Put(Bytes.toBytes(rowKey));
 93         //3.添加列簇、列、数据
 94         put.add(Bytes.toBytes(columeFamily), Bytes.toBytes(col), Bytes.toBytes(value));
 95         //4.添加到表里
 96         hTable.put(put);
 97         System.out.println(nameTable+"插入数据成功!");
 98     }
 99 
100     /**
101      * 四、扫描整张表
102      * @param tableName
103      * @throws IOException
104      */
105     public static void scanTable(String tableName) throws IOException {
106         //1.先创建HTable对象
107         HTable hTable = new HTable(conf, tableName);
108         //2.再创建Scan扫描器对象
109         Scan scan = new Scan();
110         //3.使用HTable得到scanner实现类的对象 --将获取到的数据全部存到对象里
111         ResultScanner scanner = hTable.getScanner(scan);
112         for(Result result:scanner){
113             Cell[] cells = result.rawCells();
114             for(Cell cell:cells){
115                 System.out.println("行键:"+Bytes.toString(CellUtil.cloneRow(cell))+"\t"+
116                         "列簇:"+Bytes.toString(CellUtil.cloneFamily(cell))+"\t"+
117                         "列名:"+Bytes.toString(CellUtil.cloneQualifier(cell))+"\t"+
118                         "数据:"+Bytes.toString(CellUtil.cloneValue(cell)));
119             }
120         }
121     }
122 
123     /**
124      * 五、删除表
125      * @param tableName
126      * @throws IOException
127      */
128     public static void dropTable(String tableName) throws IOException {
129         //1.在HBase中管理、访问表需要先创建HBaseAdmin对象
130         HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
131         //2.判断表是否存在
132         if(is_table_exists(tableName)){
133             hBaseAdmin.disableTable(tableName);
134             hBaseAdmin.deleteTable(tableName);
135             System.out.println(tableName+"已删除成功!");
136         }else{
137             System.out.println(tableName+"表不存在!");
138         }
139     }
140 
141     /**
142      * 六、删除多行
143      * @param tableName
144      * @param rowKey
145      * @throws IOException
146      */
147     public static void deleteMultiRow(String tableName,String... rowKey) throws IOException {
148         //1.创建HTable对象
149         HTable hTable = new HTable(conf,tableName);
150         //3.创建删除列表
151         List<Delete> deleteList = new ArrayList<>();
152         for(String row:rowKey){
153             //2.创建Delete对象
154             Delete delete = new Delete(Bytes.toBytes(row));
155             //4.将要删除的行的对象添加到删除列表中
156             deleteList.add(delete);
157         }
158         //5.针对表进行多行的删除
159         hTable.delete(deleteList);
160         //6.关闭表
161         hTable.close();
162     }
163 
164     /**
165      * 七、获取指定行键所在行的所有数据
166      * @param tableName
167      * @param rowKey
168      * @throws IOException
169      */
170     public static void getRow(String tableName,String rowKey) throws IOException {
171         //1.创建一个HTable对象
172         HTable hTable = new HTable(conf,tableName);
173         //2.创建Get对象
174         Get get = new Get(Bytes.toBytes(rowKey));
175         //get.setMaxVersions();显示所有版本
176         //get.setTimeStamp();显示指定时间戳的版本
177         //3.使用HTable得到result实现类的对象
178         Result result = hTable.get(get);
179         //4.对于每行得到各个列的值
180         for(Cell cell:result.rawCells()){
181             System.out.println("行键:"+Bytes.toString(CellUtil.cloneRow(cell))+"\t"+
182                     "列簇:"+Bytes.toString(CellUtil.cloneFamily(cell))+"\t"+
183                     "列名:"+Bytes.toString(CellUtil.cloneQualifier(cell))+"\t"+
184                     "数据:"+Bytes.toString(CellUtil.cloneValue(cell))+"\t"+
185                     "时间戳:"+cell.getTimestamp());
186         }
187     }
188 
189     /**
190      * 八、查询具体列所在行的所有数据
191      * @param tableName
192      * @param rowKey
193      * @param colFamily
194      * @param col
195      * @throws IOException
196      */
197     public static void getRowCol(String tableName,String rowKey,String colFamily,String col) throws IOException {
198         //1.创建HTable对象
199         HTable hTable = new HTable(conf, tableName);
200         //2.创建Get对象
201         Get get = new Get(Bytes.toBytes(rowKey));
202         //3.将要查询的列簇、列名传入get
203         get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
204         //4.使用HTable得到result实现类的对象
205         Result result = hTable.get(get);
206         for(Cell cell:result.rawCells()){
207             System.out.println("行键:"+Bytes.toString(result.getRow())+"\t"+
208                     "列簇:"+Bytes.toString(CellUtil.cloneFamily(cell))+"\t"+
209                     "列名:"+Bytes.toString(CellUtil.cloneQualifier(cell))+"\t"+
210                     "数据:"+Bytes.toString(CellUtil.cloneValue(cell)));
211         }
212     }
213     public static void main(String[] args) throws IOException {
214         //System.out.println(is_table_exists("student"));
215         //createTable("create1","cf1","cf2","cf3");
216         //连续插入100次数据
217 //        for(int i=0;i<100;i++){
218 //            putTable("create1",String.valueOf(i),"cf2","cr","rong"+i);
219 //        }
220         //scanTable("create1");
221         //dropTable("create1");
222         //deleteMultiRow("city","1001","1003");
223         //getRow("city","1002");
224         getRowCol("city","1002","cf","countries");
225     }
226 }

四、总结

1.在HBase中管理、访问表需要先创建HBaseAdmin对象(判断表是否存在/创建表/删除表时)

HBaseAdmin admin = new HBaseAdmin(conf);

或:

Connection connection = ConnectionFactory.createConnection(conf);

HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();

2.在读取/修改表中数据的时候(像这里的插入数据/删除多行数据/查询整张表/查询指定条件的行数据),需要创建HTable对象

//1.创建一个HTable对象
HTable hTable = new HTable(conf, nameTable);

 

博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3