Hbase配置(伪分布式模式)
1、配置文件和环境
①配置hbase-env.sh
设置Java安装路径
设置HBase的配置文件路径(/opt/module/hbase/conf)
采用HBase自带Zookeeper,设置参数true
②配置hbase-site.xml
<!--hbase共享目录,持久化hbase数据-->
<!--配置为core-site.xml 中的fs.defaultFS -->
<property>
<name>hbase.rootdir</name>
<value>hdfs://bigdata128:9000/hbase</value>
</property>
<!--分布式运行模式,false(默认)为单机模式-->
<property>
<name>hbase.cluster.distributed</name>
<value>true</value>
</property>
<!--Zookeeper集群的地址列表,伪分布式用默认localhost-->
<property>
<name>hbase.zookeeper.quorum</name>
<value>localhost</value>
</property>
③启动并运行HBase
2、进入hbase数据库
①创建表
②添加数据
③查看数据
④删除数据
⑤删除表
3、HBase架构原理
- RowKey
- TimeStamp:
- Column:
- 通过单个rowkey访问
- 通过rowkey的range
- 全表扫描
- 为HRegionServer分配HRegion
- 负责HRegionServer的负载均衡
- 发现失效的HRegionServer并重新分配
- HDFS上的垃圾文件回收
- 处理Schema更新请求
- 维护HMaster分配给它的HRegion,处理对这些HRegion的IO请求
- 负责切分正在运行过程中变得过大的HRegion
一、
几个主要 Hbase API 类和数据模型之间的对应关系:
1、 HBaseAdmin
关系: org.apache.hadoop.hbase.client.HBaseAdmin
作用:提供了一个接口来管理 HBase 数据库的表信息。它提供的方法包括:创建表,删 除表,列出表项,使表有效或无效,以及添加或删除表列族成员等。
2、 HBaseConfiguration
关系: org.apache.hadoop.hbase.HBaseConfiguration
作用:对 HBase 进行配置
3、 HTableDescriptor
关系: org.apache.hadoop.hbase.HTableDescriptor
作用:包含了表的名字极其对应表的列族
4、 HColumnDescriptor
关系: org.apache.hadoop.hbase.HColumnDescriptor
作用:维护着关于列族的信息,例如版本号,压缩设置等。它通常在创建表或者为表添 加列族的时候使用。列族被创建后不能直接修改,只能通过删除然后重新创建的方式。
列族被删除的时候,列族里面的数据也会同时被删除。
5、 HTable
关系: org.apache.hadoop.hbase.client.HTable
作用:可以用来和 HBase 表直接通信。此方法对于更新操作来说是非线程安全的。
6、 Put
关系: org.apache.hadoop.hbase.client.Put
作用:用来对单个行执行添加操作
7、 Get
关系: org.apache.hadoop.hbase.client.Get
作用:用来获取单个行的相关信息
8、 Result
关系: org.apache.hadoop.hbase.client.Result
作用:存储 Get 或者 Scan 操作后获取表的单行值。使用此类提供的方法可以直接获取值 或者各种 Map 结构( key-value 对)
二、具体增删改查 代码具体实现:
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
package HbaseDome; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Get; 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.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.Table; import org.apache.hadoop.hbase.util.Bytes; public class Hbasedome implements HBaseDemoInterface{ static Configuration conf = null ; private static final String ZKconnect= "192.168.123.212:2181,192.168.123.213:2181,192.168.123.214:2181" ; static { conf=HBaseConfiguration.create(); conf.set( "hbase.zookeeper.quorum" , ZKconnect); } // static String tableName="student"; // static String[] family={"lie01","lie02"}; public static void main(String[] args) { Hbasedome a = new Hbasedome(); String tableName= "student11" ; String[] family={ "lie01" , "lie02" }; try { HTableDescriptor htds = new HTableDescriptor(tableName); for ( int z= 0 ;z<family.length;z++){ HColumnDescriptor h= new HColumnDescriptor(family[z]); htds.addFamily(h); } // a.descTable("table03"); // a.createTable(tableName, htds); // a.descTable("table03"); // a.getAllTables(); // a.createTable(tableName,family); // a.getResult("table03", "usr001"); // a.dropTable("user1"); // a.getAllTables(); // a.putData("table03", "usr005", "liezu01", "name", "liu"); // a.getResult("table03", "usr001"); // a.getResultScann("table03"); // a.getResultScann("table03",""); Result result = a.getResult( "table03" , "usr001" ); System.out.println(result.toString()); List<Cell> cells = result.listCells(); for ( int i = 0 ; i < cells.size(); i++) { Cell cell = cells.get(i); System.out.println(cell.toString()); // printCell(cell); } // List<KeyValue> list = result.list(); // for (int i = 0; i < list.size(); i++) { // KeyValue kv = list.get(i); // printKeyValye(kv); // } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void printKeyValye(KeyValue kv) { System.out.println(Bytes.toString(kv.getRow()) + "\t" + Bytes.toString(kv.getFamily()) + "\t" + Bytes.toString(kv.getQualifier()) + "\t" + Bytes.toString(kv.getValue()) + "\t" + kv.getTimestamp()); } public static void printCell(Cell cell) { System.out.println(Bytes.toString(cell.getRow()) + "\t" + Bytes.toString(cell.getFamily()) + "\t" + Bytes.toString(cell.getQualifier()) + "\t" + Bytes.toString(cell.getValue()) + "\t" + cell.getTimestamp()); } //创建表 @Override public void createTable(String tableName, String[] family) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); HTableDescriptor desc = new HTableDescriptor(tableName); for ( int i= 0 ;i<family.length;i++){ desc.addFamily( new HColumnDescriptor(family[i])); System.out.println( "11111111111" +family[i]); } if (admin.tableExists(tableName)){ System.out.println( "表已经存在,别瞎输行吗" ); // System.exit(0); } else { admin.createTable(desc); System.out.println( "表创建成功" ); } } //创建表 @Override public void createTable(String tableName, HTableDescriptor htds) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); boolean tableExists1 = admin.tableExists(Bytes.toBytes(tableName)); System.out.println(tableExists1 ? "表已存在" : "表不存在" ); admin.createTable(htds); boolean tableExists = admin.tableExists(Bytes.toBytes(tableName)); System.out.println(tableExists ? "创建表成功" : "创建失败" ); } @Override public void descTable(String tableName) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); HTable table= new HTable(conf, tableName); HTableDescriptor desc =table.getTableDescriptor(); HColumnDescriptor[] columnFamilies = desc.getColumnFamilies(); for (HColumnDescriptor t:columnFamilies){ System.out.println(Bytes.toString(t.getName())); } } //// 这种方式是替换该表tableName的所有列簇 @Override public void modifyTable(String tableName) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName)); htd.addFamily( new HColumnDescriptor(Bytes.toBytes( "cf3" ))); htd.addFamily( new HColumnDescriptor(Bytes.toBytes( "cf2" ))); admin.modifyTable(tableName, htd); // 删除该表tableName当中的特定的列簇 // admin.deleteColumn(tableName, "cf3"); System.out.println( "修改成功" ); } @Override public void getAllTables() throws Exception { HBaseAdmin admin = new HBaseAdmin(conf); String[] tableNames = admin.getTableNames(); for ( int i= 0 ;i<tableNames.length;i++){ System.out.println(tableNames[i]); } } //更新数据 插入数据 @Override public void putData(String tableName, String rowKey, String familyName, String columnName, String value) throws Exception { HTable htable= new HTable(conf, Bytes.toBytes(tableName)); Put put= new Put(Bytes.toBytes(rowKey)); put.add(Bytes.toBytes(familyName), Bytes.toBytes(columnName), Bytes.toBytes(value)); htable.put(put); } //为表添加数据 @Override public void addData(String tableName, String rowKey, String[] column1, String[] value1, String[] column2, String[] value2) throws Exception { Put put= new Put(Bytes.toBytes(rowKey)); HTable htable= new HTable(conf, Bytes.toBytes(tableName)); HColumnDescriptor[] columnFamilies = htable.getTableDescriptor().getColumnFamilies(); for ( int i= 0 ;i<=columnFamilies.length;i++){ String nameAsString = columnFamilies[i].getNameAsString(); if (nameAsString.equals( "lie01" )){ for ( int j= 0 ;j<column1.length;j++){ put.add(Bytes.toBytes(nameAsString), Bytes.toBytes(column1[j]),Bytes.toBytes(value1[j])); } } if (nameAsString.equals( "lie02" )){ for ( int j= 0 ;j<column2.length;j++){ put.add(Bytes.toBytes(nameAsString), Bytes.toBytes(column2[j]),Bytes.toBytes(value2[j])); } } } htable.put(put); System.out.println( "addData ok!" ); } //根据rowkey 查询 @Override public Result getResult(String tableName, String rowKey) throws Exception { Get get= new Get(Bytes.toBytes(rowKey)); HTable htable= new HTable(conf, Bytes.toBytes(tableName)); Result result=htable.get(get); // for(KeyValue k:result.list()){ // System.out.println(Bytes.toString(k.getFamily())); // System.out.println(Bytes.toString(k.getQualifier())); // System.out.println(Bytes.toString(k.getValue())); // System.out.println(k.getTimestamp()); // } return result; } //查询指定的某列 @Override public Result getResult(String tableName, String rowKey, String familyName, String columnName) throws Exception { Get get= new Get(Bytes.toBytes(rowKey)); HTable htable= new HTable(conf, Bytes.toBytes(tableName)); get.addColumn(Bytes.toBytes(familyName),Bytes.toBytes(columnName)); Result result=htable.get(get); for (KeyValue k:result.list()){ System.out.println(Bytes.toString(k.getFamily())); System.out.println(Bytes.toString(k.getQualifier())); System.out.println(Bytes.toString(k.getValue())); System.out.println(k.getTimestamp()); } return result; } //遍历查询表 @Override public ResultScanner getResultScann(String tableName) throws Exception { Scan scan= new Scan(); ResultScanner rs = null ; HTable htable= new HTable(conf, tableName); try { rs=htable.getScanner(scan); for (Result r: rs){ for (KeyValue kv:r.list()){ System.out.println(Bytes.toString(kv.getRow())); System.out.println(Bytes.toString(kv.getFamily())); System.out.println(Bytes.toString(kv.getQualifier())); System.out.println(Bytes.toString(kv.getValue())); System.out.println(kv.getTimestamp()); } } } finally { rs.close(); } return rs; } @Override public ResultScanner getResultScann(String tableName, Scan scan) throws Exception { ResultScanner rs = null ; HTable htable= new HTable(conf, tableName); try { rs=htable.getScanner(scan); for (Result r: rs){ for (KeyValue kv:r.list()){ System.out.println(Bytes.toString(kv.getRow())); System.out.println(Bytes.toString(kv.getFamily())); System.out.println(Bytes.toString(kv.getQualifier())); System.out.println(Bytes.toString(kv.getValue())); System.out.println(kv.getTimestamp()); } } } finally { rs.close(); } return rs; } //查询表中的某一列 @Override public Result getResultByColumn(String tableName, String rowKey, String familyName, String columnName) throws Exception { HTable htable= new HTable(conf, tableName); Get get= new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(familyName),Bytes.toBytes(columnName)); Result result=htable.get(get); for (KeyValue kv: result.list()){ System.out.println(Bytes.toString(kv.getFamily())); System.out.println(Bytes.toString(kv.getQualifier())); System.out.println(Bytes.toString(kv.getValue())); System.out.println(kv.getTimestamp()); } return result; } //查询某列数据的某个版本 @Override public Result getResultByVersion(String tableName, String rowKey, String familyName, String columnName, int versions) throws Exception { HTable htable= new HTable(conf, tableName); Get get = new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName)); get.setMaxVersions(versions); Result result=htable.get(get); for (KeyValue kv: result.list()){ System.out.println(Bytes.toString(kv.getFamily())); System.out.println(Bytes.toString(kv.getQualifier())); System.out.println(Bytes.toString(kv.getValue())); System.out.println(kv.getTimestamp()); } return result; } //删除指定某列 @Override public void deleteColumn(String tableName, String rowKey, String falilyName, String columnName) throws Exception { HTable htable= new HTable(conf, tableName); // Delete delete1=new Delete(Bytes.toBytes(rowKey)); Delete de = new Delete(Bytes.toBytes(rowKey)); de.deleteColumn(Bytes.toBytes(falilyName), Bytes.toBytes(columnName)); htable.delete(de); } //删除指定的某个rowkey @Override public void deleteColumn(String tableName, String rowKey) throws Exception { HTable htable= new HTable(conf, tableName); Delete de = new Delete(Bytes.toBytes(rowKey)); htable.delete(de); } //让该表失效 @Override public void disableTable(String tableName) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); admin.disableTable(tableName); } //删除表 @Override public void dropTable(String tableName) throws Exception { HBaseAdmin admin= new HBaseAdmin(conf); admin.disableTable(tableName); admin.deleteTable(tableName); } } |
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
|
package com.ghgj.hbase.test1610; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; 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.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; public class HBaseAPIDemo1610 implements HBaseDemoInterface { private static final String ROWKEY = "p001" ; private static final String ROWKEY2 = "p002" ; private static final String FAMILY1 = "cf1" ; private static final String FAMILY2 = "cf2" ; private static final String KEY = "name" ; private static final String VALUE = "huangbo" ; private static final String TABLE_NAME = "person" ; private static final String[] COLUMN_FAMILY = new String[] { FAMILY1, FAMILY2 }; static Configuration conf = null ; static HBaseAdmin admin = null ; static HTable table = null ; static { try { conf = HBaseConfiguration.create(); conf.set( "hbase.zookeeper.quorum" , "hadoop03:2181,hadoop04:2181,hadoop05:2181" ); admin = new HBaseAdmin(conf); table = new HTable(conf, TABLE_NAME); } catch (IOException e) { // e.printStackTrace(); System.out.println( "报错" ); } } public static void main(String[] args) throws Exception { HBaseAPIDemo1610 hbase = new HBaseAPIDemo1610(); // 测试创建表 hbase.createTable(TABLE_NAME, COLUMN_FAMILY); // 测试创建表 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(TABLE_NAME)); for ( int i = 0 ; i < COLUMN_FAMILY.length; i++) { HColumnDescriptor cf1 = new HColumnDescriptor(COLUMN_FAMILY[i]); htd.addFamily(cf1); } hbase.createTable(TABLE_NAME, htd); // 查看表属性 hbase.descTable(TABLE_NAME); // 查询所有的表 hbase.getAllTables(); // 测试修改表 hbase.modifyTable(TABLE_NAME); // 插入数据 hbase.putData(TABLE_NAME, ROWKEY, FAMILY1, KEY, VALUE); // 测试插入一堆数据 String[] column1 = new String[] { "name1" , "age" , "province" }; String[] value1 = new String[] { "huangbo" , "33" , "xinjiang" }; String[] column2 = new String[] { "gender" }; String[] value2 = new String[] { "male" }; hbase.addData(TABLE_NAME, ROWKEY2, column1, value1, column2, value2); // 通过rowkey查询数据 Result result = hbase.getResult(TABLE_NAME, ROWKEY2); System.out.println(result.toString()); List<KeyValue> list = result.list(); for ( int i = 0 ; i < list.size(); i++) { KeyValue kv = list.get(i); printKeyValye(kv); } // 通过rowkey, family, province查询数据 Result result1 = hbase.getResult(TABLE_NAME, ROWKEY2, FAMILY1, "province" ); List<Cell> cells = result1.listCells(); for ( int i = 0 ; i < cells.size(); i++) { Cell cell = cells.get(i); printCell(cell); } // 扫描全表数据 ResultScanner resultScann = hbase.getResultScann(TABLE_NAME); printResultScanner(resultScann); /*Iterator<Result> iterator = resultScann.iterator(); while(iterator.hasNext()){ Result next = iterator.next(); }*/ // 通过scan扫描全表数据,scan中可以加入一些过滤条件 Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes( "user" )); scan.setStopRow(Bytes.toBytes( "zk002" )); scan.setTimeRange(1488252774189l, 1488252774191l); ResultScanner resultScann1 = hbase.getResultScann(TABLE_NAME, scan); printResultScanner(resultScann1); // 两种方式查询最大版本数的hbase数据 Result resultByVersion = hbase.getResultByVersion(TABLE_NAME, ROWKEY, FAMILY1, "name" , 3 ); printResult(resultByVersion); System.out.println( "-------------------" ); ResultScanner rs = hbase.getResultByVersion(ROWKEY, FAMILY1, "name" , 3 ); printResultScanner(rs); // 删除表 hbase.dropTable(TABLE_NAME); } public static void printResultScanner(ResultScanner resultScann) { for (Result result : resultScann) { printResult(result); } } public static void printResult(Result result) { List<Cell> cells = result.listCells(); for ( int i = 0 ; i < cells.size(); i++) { Cell cell = cells.get(i); printCell(cell); } } public static void printCell(Cell cell) { System.out.println(Bytes.toString(cell.getRow()) + "\t" + Bytes.toString(cell.getFamily()) + "\t" + Bytes.toString(cell.getQualifier()) + "\t" + Bytes.toString(cell.getValue()) + "\t" + cell.getTimestamp()); } public static void printKeyValye(KeyValue kv) { System.out.println(Bytes.toString(kv.getRow()) + "\t" + Bytes.toString(kv.getFamily()) + "\t" + Bytes.toString(kv.getQualifier()) + "\t" + Bytes.toString(kv.getValue()) + "\t" + kv.getTimestamp()); } // create 'tablename','cf1','cf2' @Override public void createTable(String tableName, String[] family) throws Exception { HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName)); for ( int i = 0 ; i < family.length; i++) { HColumnDescriptor cf1 = new HColumnDescriptor(family[i]); htd.addFamily(cf1); } admin.createTable(htd); boolean tableExists = admin.tableExists(Bytes.toBytes(tableName)); System.out.println(tableExists ? "创建表成功" : "创建失败" ); } @Override public void createTable(String tableName, HTableDescriptor htd) throws Exception { admin.createTable(htd); boolean tableExists = admin.tableExists(Bytes.toBytes(tableName)); System.out.println(tableExists ? "创建表成功" : "创建失败" ); } // desc 'person' @Override public void descTable(String tableName) throws Exception { HTableDescriptor tableDescriptor = table.getTableDescriptor(); HColumnDescriptor[] columnFamilies = tableDescriptor.getColumnFamilies(); for (HColumnDescriptor hcd : columnFamilies) { // System.out.println(hcd.toString()+"\t"); System.out.println(Bytes.toString(hcd.getName())); } } @Override public void modifyTable(String tableName) throws Exception { // 这种方式是替换该表tableName的所有列簇 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName)); htd.addFamily( new HColumnDescriptor(Bytes.toBytes( "cf3" ))); htd.addFamily( new HColumnDescriptor(Bytes.toBytes( "cf2" ))); admin.modifyTable(tableName, htd); // 删除该表tableName当中的特定的列簇 // admin.deleteColumn(tableName, "cf3"); System.out.println( "修改成功" ); } // list @Override public void getAllTables() throws Exception { TableName[] listTableNames = admin.listTableNames(); for (TableName tn : listTableNames) { System.out.println(tn.toString()); } } // put 'tablename','rowkey','familyname:key','value' @Override public void putData(String tableName, String rowKey, String familyName, String columnName, String value) throws Exception { // HTable table = new HTable(conf, tableName); Put put = new Put(Bytes.toBytes(rowKey)); put.add(Bytes.toBytes(familyName), Bytes.toBytes(columnName), Bytes.toBytes(value)); table.put(put); System.out.println( "插入成功" ); } /** * @param tableName * 表名 * @param rowKey * rowkey * @param column1 * 第一个列簇的key数组 * @param value1 * 第一个列簇的value数组,key数组和value数组长度必须一样 * @param column2 * 第二列簇的key数组 * @param value2 * 第二个列簇的values数组, 同上同理 * @throws Exception */ @Override public void addData(String tableName, String rowKey, String[] column1, String[] value1, String[] column2, String[] value2) throws Exception { List<Put> puts = new ArrayList<Put>(); for ( int i = 0 ; i < column1.length; i++) { Put put = new Put(Bytes.toBytes(rowKey)); put.add(Bytes.toBytes(FAMILY1), Bytes.toBytes(column1[i]), Bytes.toBytes(value1[i])); puts.add(put); } for ( int i = 0 ; i < column2.length; i++) { Put put = new Put(Bytes.toBytes(rowKey)); put.add(Bytes.toBytes(FAMILY2), Bytes.toBytes(column2[i]), Bytes.toBytes(value2[i])); puts.add(put); } table.put(puts); System.out.println( "插入一堆数据成功" ); } // get 'tablename','rowkey' @Override public Result getResult(String tableName, String rowKey) throws Exception { Get get = new Get(Bytes.toBytes(rowKey)); Result result = table.get(get); return result; } @Override public Result getResult(String tableName, String rowKey, String familyName, String columnName) throws Exception { Get get = new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName)); Result result = table.get(get); return result; } @Override public ResultScanner getResultScann(String tableName) throws Exception { Scan scan = new Scan(); ResultScanner scanner = table.getScanner(scan); // ResultScanner scanner = table.getScanner(Bytes.toBytes(FAMILY2)); // ResultScanner scanner = table.getScanner(Bytes.toBytes(FAMILY1), // Bytes.toBytes("name1")); return scanner; } @Override public ResultScanner getResultScann(String tableName, Scan scan) throws Exception { return table.getScanner(scan); } @Override public Result getResultByColumn(String tableName, String rowKey, String familyName, String columnName) throws Exception { return null ; } // get 'person','p001',{COLUMNS => 'cf1:name', VERSIONS => 3} @Override public Result getResultByVersion(String tableName, String rowKey, String familyName, String columnName, int versions) throws Exception { Get get = new Get(Bytes.toBytes(rowKey)); get.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName)); get.setMaxVersions(versions); Result result = table.get(get); return result; } public ResultScanner getResultByVersion(String rowKey, String familyName, String columnName, int versions) throws Exception { Scan scan = new Scan(Bytes.toBytes(rowKey), Bytes.toBytes(rowKey)); scan.addColumn(Bytes.toBytes(familyName), Bytes.toBytes(columnName)); scan.setMaxVersions(versions); ResultScanner scanner = table.getScanner(scan); return scanner; } @Override public void deleteColumn(String tableName, String rowKey, String falilyName, String columnName) throws Exception { } @Override public void deleteColumn(String tableName, String rowKey) throws Exception { } @Override public void disableTable(String tableName) throws Exception { admin.disableTable(tableName); } @Override public void dropTable(String tableName) throws Exception { try { admin.deleteTable(tableName); } catch (Exception e) { // e.printStackTrace(); disableTable(tableName); admin.deleteTable(tableName); System.out.println( "ssssssss" ); } finally { boolean tableExists = admin.tableExists(Bytes.toBytes(tableName)); System.out.println(tableExists ? "删除失败" : "删除成功" ); } } } hh |
Hbase Java API详解
HBase是Hadoop的数据库,能够对大数据提供随机、实时读写访问。他是开源的,分布式的,多版本的,面向列的,存储模型。
在讲解的时候我首先给大家讲解一下HBase的整体结构,如下图:
HBase Master是服务器负责管理所有的HRegion服务器,HBase Master并不存储HBase服务器的任何数据,HBase逻辑上的表可能会划分为多个HRegion,然后存储在HRegion Server群中,HBase Master Server中存储的是从数据到HRegion Server的映射。
一台机器只能运行一个HRegion服务器,数据的操作会记录在Hlog中,在读取数据时候,HRegion会先访问Hmemcache缓存,如果 缓存中没有数据才回到Hstore中上找,没一个列都会有一个Hstore集合,每个Hstore集合包含了很多具体的HstoreFile文件,这些文 件是B树结构的,方便快速读取。
再看下HBase数据物理视图如下:
Row Key | Timestamp | Column Family | |
URI | Parser | ||
r1 | t3 | url=http://www.taobao.com | title=天天特价 |
t2 | host=taobao.com | ||
t1 | |||
r2 | t5 | url=http://www.alibaba.com | content=每天… |
t4 | host=alibaba.com |
Ø Row Key: 行键,Table的主键,Table中的记录按照Row Key排序
Ø Timestamp: 时间戳,每次数据操作对应的时间戳,可以看作是数据的version number
Ø Column Family:列簇,Table在水平方向有一个或者多个Column Family组成,一个Column Family中可以由任意多个Column组成,即Column Family支持动态扩展,无需预先定义Column的数量以及类型,所有Column均以二进制格式存储,用户需要自行进行类型转换。
了解了HBase的体系结构和HBase数据视图够,现在让我们一起看看怎样通过Java来操作HBase数据吧!
先说说具体的API先,如下
HBaseConfiguration是每一个hbase client都会使用到的对象,它代表的是HBase配置信息。它有两种构造方式:
public HBaseConfiguration()
public HBaseConfiguration(final Configuration c)
默认的构造方式会尝试从hbase-default.xml和hbase-site.xml中读取配置。如果classpath没有这两个文件,就需要你自己设置配置。
Configuration HBASE_CONFIG = new Configuration();
HBASE_CONFIG.set(“hbase.zookeeper.quorum”, “zkServer”);
HBASE_CONFIG.set(“hbase.zookeeper.property.clientPort”, “2181″);
HBaseConfiguration cfg = new HBaseConfiguration(HBASE_CONFIG);
创建表
创建表是通过HBaseAdmin对象来操作的。HBaseAdmin负责表的META信息处理。HBaseAdmin提供了createTable这个方法:
public void createTable(HTableDescriptor desc)
HTableDescriptor 代表的是表的schema, 提供的方法中比较有用的有
setMaxFileSize,指定最大的region size
setMemStoreFlushSize 指定memstore flush到HDFS上的文件大小
增加family通过 addFamily方法
public void addFamily(final HColumnDescriptor family)
HColumnDescriptor 代表的是column的schema,提供的方法比较常用的有
setTimeToLive:指定最大的TTL,单位是ms,过期数据会被自动删除。
setInMemory:指定是否放在内存中,对小表有用,可用于提高效率。默认关闭
setBloomFilter:指定是否使用BloomFilter,可提高随机查询效率。默认关闭
setCompressionType:设定数据压缩类型。默认无压缩。
setMaxVersions:指定数据最大保存的版本个数。默认为3。
一个简单的例子,创建了4个family的表:
HBaseAdmin hAdmin = new HBaseAdmin(hbaseConfig); HTableDescriptor t = new HTableDescriptor(tableName); t.addFamily(new HColumnDescriptor(“f1″)); t.addFamily(new HColumnDescriptor(“f2″)); t.addFamily(new HColumnDescriptor(“f3″)); t.addFamily(new HColumnDescriptor(“f4″)); hAdmin.createTable(t);
删除表
删除表也是通过HBaseAdmin来操作,删除表之前首先要disable表。这是一个非常耗时的操作,所以不建议频繁删除表。
disableTable和deleteTable分别用来disable和delete表。
Example:
HBaseAdmin hAdmin = new HBaseAdmin(hbaseConfig); if (hAdmin.tableExists(tableName)) { hAdmin.disableTable(tableName); hAdmin.deleteTable(tableName); }
查询数据
查询分为单条随机查询和批量查询。
单条查询是通过rowkey在table中查询某一行的数据。HTable提供了get方法来完成单条查询。
批量查询是通过制定一段rowkey的范围来查询。HTable提供了个getScanner方法来完成批量查询。
public Result get(final Get get)
public ResultScanner getScanner(final Scan scan)
Get对象包含了一个Get查询需要的信息。它的构造方法有两种:
public Get(byte [] row)
public Get(byte [] row, RowLock rowLock)
Rowlock是为了保证读写的原子性,你可以传递一个已经存在Rowlock,否则HBase会自动生成一个新的rowlock。
Scan对象提供了默认构造函数,一般使用默认构造函数。
Get/Scan的常用方法有:
addFamily/addColumn:指定需要的family或者column,如果没有调用任何addFamily或者Column,会返回所有的columns.
setMaxVersions:指定最大的版本个数。如果不带任何参数调用setMaxVersions,表示取所有的版本。如果不掉用setMaxVersions,只会取到最新的版本。
setTimeRange:指定最大的时间戳和最小的时间戳,只有在此范围内的cell才能被获取。
setTimeStamp:指定时间戳。
setFilter:指定Filter来过滤掉不需要的信息
Scan特有的方法:
setStartRow:指定开始的行。如果不调用,则从表头开始。
setStopRow:指定结束的行(不含此行)。
setBatch:指定最多返回的Cell数目。用于防止一行中有过多的数据,导致OutofMemory错误。
ResultScanner是Result的一个容器,每次调用ResultScanner的next方法,会返回Result.
public Result next() throws IOException;
public Result [] next(int nbRows) throws IOException;
Result代表是一行的数据。常用方法有:
getRow:返回rowkey
raw:返回所有的key value数组。
getValue:按照column来获取cell的值
Example:
Scan s = new Scan(); s.setMaxVersions(); ResultScanner ss = table.getScanner(s); for(Result r:ss){ System.out.println(new String(r.getRow())); for(KeyValue kv:r.raw()){ System.out.println(new String(kv.getColumn())); } }
插入数据
HTable通过put方法来插入数据。
public void put(final Put put) throws IOException
public void put(final List puts) throws IOException
可以传递单个批Put对象或者List put对象来分别实现单条插入和批量插入。
Put提供了3种构造方式:
public Put(byte [] row)
public Put(byte [] row, RowLock rowLock)
public Put(Put putToCopy)
Put常用的方法有:
add:增加一个Cell
setTimeStamp:指定所有cell默认的timestamp,如果一个Cell没有指定timestamp,就会用到这个值。如果没有调用,HBase会将当前时间作为未指定timestamp的cell的timestamp.
setWriteToWAL: WAL是Write Ahead Log的缩写,指的是HBase在插入操作前是否写Log。默认是打开,关掉会提高性能,但是如果系统出现故障(负责插入的Region Server挂掉),数据可能会丢失。
另外HTable也有两个方法也会影响插入的性能
setAutoFlash: AutoFlush指的是在每次调用HBase的Put操作,是否提交到HBase Server。默认是true,每次会提交。如果此时是单条插入,就会有更多的IO,从而降低性能.
setWriteBufferSize: Write Buffer Size在AutoFlush为false的时候起作用,默认是2MB,也就是当插入数据超过2MB,就会自动提交到Server
Example:
HTable table = new HTable(hbaseConfig, tableName); table.setAutoFlush(autoFlush); List lp = new ArrayList(); int count = 10000; byte[] buffer = new byte[1024]; Random r = new Random(); for (int i = 1; i <= count; ++i) { Put p = new Put(String.format(“row%09d”,i).getBytes()); r.nextBytes(buffer); p.add(“f1″.getBytes(), null, buffer); p.add(“f2″.getBytes(), null, buffer); p.add(“f3″.getBytes(), null, buffer); p.add(“f4″.getBytes(), null, buffer); p.setWriteToWAL(wal); lp.add(p); if(i%1000==0){ table.put(lp); lp.clear(); } }
删除数据
HTable 通过delete方法来删除数据。
public void delete(final Delete delete)
Delete构造方法有:
public Delete(byte [] row)
public Delete(byte [] row, long timestamp, RowLock rowLock)
public Delete(final Delete d)
Delete常用方法有
deleteFamily/deleteColumns:指定要删除的family或者column的数据。如果不调用任何这样的方法,将会删除整行。
注意:如果某个Cell的timestamp高于当前时间,这个Cell将不会被删除,仍然可以查出来。
Example:
HTable table = new HTable(hbaseConfig, “mytest”); Delete d = new Delete(“row1″.getBytes()); table.delete(d)
切分表
HBaseAdmin提供split方法来将table 进行split.
public void split(final String tableNameOrRegionName)
如果提供的tableName,那么会将table所有region进行split ;如果提供的region Name,那么只会split这个region.
由于split是一个异步操作,我们并不能确切的控制region的个数。
Example:
public void split(String tableName,int number,int timeout) throws Exception { Configuration HBASE_CONFIG = new Configuration(); HBASE_CONFIG.set(“hbase.zookeeper.quorum”, GlobalConf.ZOOKEEPER_QUORUM); HBASE_CONFIG.set(“hbase.zookeeper.property.clientPort”, GlobalConf.ZOOKEEPER_PORT); HBaseConfiguration cfg = new HBaseConfiguration(HBASE_CONFIG); HBaseAdmin hAdmin = new HBaseAdmin(cfg); HTable hTable = new HTable(cfg,tableName); int oldsize = 0; t = System.currentTimeMillis(); while(true){ int size = hTable.getRegionsInfo().size(); logger.info(“the region number=”+size); if(size>=number ) break; if(size!=oldsize){ hAdmin.split(hTable.getTableName()); oldsize = size; } else if(System.currentTimeMillis()-t>timeout){ break; } Thread.sleep(1000*10); } }