---
title: "HBASE"
author: "hougbin"
date: "2012-07-26T15:05:51Z"
tags: []
categories: ["数据库"]
slug: "hbase"
draft: false
lastmod: "2012-07-26T15:05:51Z"
id: 1607959
url: "https://hougbin.iteye.com/blog/1607959"
---

1、搭建环境

新建JAVA项目，添加的包有:

有关Hadoop的hadoop-core-0.20.204.0.jar

有关Hbase的hbase-0.90.4.jar、hbase-0.90.4-tests.jar以及Hbase资源包中lib目录下的所有jar包

 

2、主要程序

 

Java代码

001. package com.wujintao.hbase.test;
002. import java.io.IOException;
003. import java.util.ArrayList;
004. import java.util.List;
005. import org.apache.hadoop.conf.Configuration;
006. import org.apache.hadoop.hbase.HBaseConfiguration;
007. import org.apache.hadoop.hbase.HColumnDescriptor;
008. import org.apache.hadoop.hbase.HTableDescriptor;
009. import org.apache.hadoop.hbase.KeyValue;
010. import org.apache.hadoop.hbase.MasterNotRunningException;
011. import org.apache.hadoop.hbase.ZooKeeperConnectionException;
012. import org.apache.hadoop.hbase.client.Delete;
013. import org.apache.hadoop.hbase.client.Get;
014. import org.apache.hadoop.hbase.client.HBaseAdmin;
015. import org.apache.hadoop.hbase.client.HTable;
016. import org.apache.hadoop.hbase.client.HTablePool;
017. import org.apache.hadoop.hbase.client.Put;
018. import org.apache.hadoop.hbase.client.Result;
019. import org.apache.hadoop.hbase.client.ResultScanner;
020. import org.apache.hadoop.hbase.client.Scan;
021. import org.apache.hadoop.hbase.filter.Filter;
022. import org.apache.hadoop.hbase.filter.FilterList;
023. import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
024. import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
025. import org.apache.hadoop.hbase.util.Bytes;
026. public class JinTaoTest {
027. public static Configuration configuration;
028. static {
029. configuration = HBaseConfiguration.create();
030. configuration.set("hbase.zookeeper.property.clientPort", "2181");
031. configuration.set("hbase.zookeeper.quorum", "192.168.1.100");
032. configuration.set("hbase.master", "192.168.1.100:600000");
033. }
034. public static void main(String\[] args) {
035. // createTable("wujintao");
036. // insertData("wujintao");
037. // QueryAll("wujintao");
038. // QueryByCondition1("wujintao");
039. // QueryByCondition2("wujintao");
040. //QueryByCondition3("wujintao");
041. //deleteRow("wujintao","abcdef");
042. deleteByCondition("wujintao","abcdef");
043. }
044. /\**
045. \* 创建表
046. \* @param tableName
047. \*/
048. public static void createTable(String tableName) {
049. System.out.println("start create table ......");
050. try {
051. HBaseAdmin hBaseAdmin = new HBaseAdmin(configuration);
052. if (hBaseAdmin.tableExists(tableName)) {// 如果存在要创建的表，那么先删除，再创建
053. hBaseAdmin.disableTable(tableName);
054. hBaseAdmin.deleteTable(tableName);
055. System.out.println(tableName + " is exist,detele....");
056. }
057. HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
058. tableDescriptor.addFamily(new HColumnDescriptor("column1"));
059. tableDescriptor.addFamily(new HColumnDescriptor("column2"));
060. tableDescriptor.addFamily(new HColumnDescriptor("column3"));
061. hBaseAdmin.createTable(tableDescriptor);
062. } catch (MasterNotRunningException e) {
063. e.printStackTrace();
064. } catch (ZooKeeperConnectionException e) {
065. e.printStackTrace();
066. } catch (IOException e) {
067. e.printStackTrace();
068. }
069. System.out.println("end create table ......");
070. }
071. /\**
072. \* 插入数据
073. \* @param tableName
074. \*/
075. public static void insertData(String tableName) {
076. System.out.println("start insert data ......");
077. HTablePool pool = new HTablePool(configuration, 1000);
078. HTable table = (HTable) pool.getTable(tableName);
079. Put put = new Put("112233bbbcccc".getBytes());// 一个PUT代表一行数据，再NEW一个PUT表示第二行数据,每行一个唯一的ROWKEY，此处rowkey为put构造方法中传入的值
080. put.add("column1".getBytes(), null, "aaa".getBytes());// 本行数据的第一列
081. put.add("column2".getBytes(), null, "bbb".getBytes());// 本行数据的第三列
082. put.add("column3".getBytes(), null, "ccc".getBytes());// 本行数据的第三列
083. try {
084. table.put(put);
085. } catch (IOException e) {
086. e.printStackTrace();
087. }
088. System.out.println("end insert data ......");
089. }
090. /\**
091. \* 删除一张表
092. \* @param tableName
093. \*/
094. public static void dropTable(String tableName) {
095. try {
096. HBaseAdmin admin = new HBaseAdmin(configuration);
097. admin.disableTable(tableName);
098. admin.deleteTable(tableName);
099. } catch (MasterNotRunningException e) {
100. e.printStackTrace();
101. } catch (ZooKeeperConnectionException e) {
102. e.printStackTrace();
103. } catch (IOException e) {
104. e.printStackTrace();
105. }
106. }
107. /\**
108. \* 根据 rowkey删除一条记录
109. \* @param tablename
110. \* @param rowkey
111. \*/
112. public static void deleteRow(String tablename, String rowkey) {
113. try {
114. HTable table = new HTable(configuration, tablename);
115. List list = new ArrayList();
116. Delete d1 = new Delete(rowkey.getBytes());
117. list.add(d1);
118. table.delete(list);
119. System.out.println("删除行成功!");
120. } catch (IOException e) {
121. e.printStackTrace();
122. }
123. }
124. /\**
125. \* 组合条件删除
126. \* @param tablename
127. \* @param rowkey
128. \*/
129. public static void deleteByCondition(String tablename, String rowkey) {
130. //目前还没有发现有效的API能够实现 根据非rowkey的条件删除 这个功能能，还有清空表全部数据的API操作
131. }
132. /\**
133. \* 查询所有数据
134. \* @param tableName
135. \*/
136. public static void QueryAll(String tableName) {
137. HTablePool pool = new HTablePool(configuration, 1000);
138. HTable table = (HTable) pool.getTable(tableName);
139. try {
140. ResultScanner rs = table.getScanner(new Scan());
141. for (Result r : rs) {
142. System.out.println("获得到rowkey:" + new String(r.getRow()));
143. for (KeyValue keyValue : r.raw()) {
144. System.out.println("列：" + new String(keyValue.getFamily())
145. \+ "====值:" + new String(keyValue.getValue()));
146. }
147. }
148. } catch (IOException e) {
149. e.printStackTrace();
150. }
151. }
152. /\**
153. \* 单条件查询,根据rowkey查询唯一一条记录
154. \* @param tableName
155. \*/
156. public static void QueryByCondition1(String tableName) {
157. HTablePool pool = new HTablePool(configuration, 1000);
158. HTable table = (HTable) pool.getTable(tableName);
159. try {
160. Get scan = new Get("abcdef".getBytes());// 根据rowkey查询
161. Result r = table.get(scan);
162. System.out.println("获得到rowkey:" + new String(r.getRow()));
163. for (KeyValue keyValue : r.raw()) {
164. System.out.println("列：" + new String(keyValue.getFamily())
165. \+ "====值:" + new String(keyValue.getValue()));
166. }
167. } catch (IOException e) {
168. e.printStackTrace();
169. }
170. }
171. /\**
172. \* 单条件按查询，查询多条记录
173. \* @param tableName
174. \*/
175. public static void QueryByCondition2(String tableName) {
176. try {
177. HTablePool pool = new HTablePool(configuration, 1000);
178. HTable table = (HTable) pool.getTable(tableName);
179. Filter filter = new SingleColumnValueFilter(Bytes
180. .toBytes("column1"), null, CompareOp.EQUAL, Bytes
181. .toBytes("aaa")); // 当列column1的值为aaa时进行查询
182. Scan s = new Scan();
183. s.setFilter(filter);
184. ResultScanner rs = table.getScanner(s);
185. for (Result r : rs) {
186. System.out.println("获得到rowkey:" + new String(r.getRow()));
187. for (KeyValue keyValue : r.raw()) {
188. System.out.println("列：" + new String(keyValue.getFamily())
189. \+ "====值:" + new String(keyValue.getValue()));
190. }
191. }
192. } catch (Exception e) {
193. e.printStackTrace();
194. }
195. }
196. /\**
197. \* 组合条件查询
198. \* @param tableName
199. \*/
200. public static void QueryByCondition3(String tableName) {
201. try {
202. HTablePool pool = new HTablePool(configuration, 1000);
203. HTable table = (HTable) pool.getTable(tableName);
204. List&lt;Filter&gt; filters = new ArrayList&lt;Filter&gt;();
205. Filter filter1 = new SingleColumnValueFilter(Bytes
206. .toBytes("column1"), null, CompareOp.EQUAL, Bytes
207. .toBytes("aaa"));
208. filters.add(filter1);
209. Filter filter2 = new SingleColumnValueFilter(Bytes
210. .toBytes("column2"), null, CompareOp.EQUAL, Bytes
211. .toBytes("bbb"));
212. filters.add(filter2);
213. Filter filter3 = new SingleColumnValueFilter(Bytes
214. .toBytes("column3"), null, CompareOp.EQUAL, Bytes
215. .toBytes("ccc"));
216. filters.add(filter3);
217. FilterList filterList1 = new FilterList(filters);
218. Scan scan = new Scan();
219. scan.setFilter(filterList1);
220. ResultScanner rs = table.getScanner(scan);
221. for (Result r : rs) {
222. System.out.println("获得到rowkey:" + new String(r.getRow()));
223. for (KeyValue keyValue : r.raw()) {
224. System.out.println("列：" + new String(keyValue.getFamily())
225. \+ "====值:" + new String(keyValue.getValue()));
226. }
227. }
228. rs.close();
229. } catch (Exception e) {
230. e.printStackTrace();
231. }
232. }
233. }

注意：可能大家没看到更新数据的操作，其实更新的操作跟添加完全一致，只不过是添加呢rowkey不存在，更新呢rowkey已经存在，并且timstamp相同的情况下，还有就是目前好像还没办法实现hbase数据的分页查询，不知道有没有人知道怎么做

 

**HBase性能优化建议：**

针对前面的代码，有很多不足之处，在此我就不修改上面的代码了，只是提出建议的地方，大家自己加上

1)配置

当你调用create方法时将会加载两个配置文件:hbase-default.xml and hbase-site.xml,利用的是当前的java类路径， 代码中configuration设置的这些配置将会覆盖hbase-default.xml和hbase-site.xml中相同的配置,如果两个配置文件都存在并且都设置好了相应参上面的属性下面的属性即可

 

2)关于建表

 

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。

 

注意的是，一般我们不去setInMemory为true,默认是关闭的

 

3)关于入库

官方建议

table.setAutoFlush(false); //数据入库之前先设置此项为false

table.setflushCommits();//入库完成后，手动刷入数据

注意：

在入库过程中，put.setWriteToWAL(true/flase);

关于这一项如果不希望大量数据在存储过程中丢失，建议设置为true,如果仅是在测试演练阶段，为了节省入库时间建议设置为false

 

4)关于获取表实例

HTablePool pool = new HTablePool(configuration, Integer.MAX\_VALUE);

HTable table = (HTable) pool.getTable(tableName);

建议用表连接池的方式获取表，具体池有什么作用，我想用过数据库连接池的同学都知道，我就不再重复

不建议使用new HTable(configuration,tableName);的方式获取表

 

5)关于查询

建议每个查询语句都放入try catch语句块，并且finally中要进行关闭ResultScanner实例以及将不使用的表重新放入到HTablePool中的操作，具体做法如下

 

Java代码

01. public static void QueryAll(String tableName) {
02. HTablePool pool = new HTablePool(configuration, Integer.MAX\_VALUE);
03. HTable table = null;
04. ResultScanner rs = null;
05. try {
06. Scan scan = new Scan();
07. table = (HTable) pool.getTable(tableName);
08. rs = table.getScanner(scan);
09. for (Result r : rs) {
10. System.out.println("获得到rowkey:" + new String(r.getRow()));
11. for (KeyValue keyValue : r.raw()) {
12. System.out.println("列：" + new String(keyValue.getFamily())
13. \+ "====值:" + new String(keyValue.getValue()));
14. }
15. }
16. } catch (IOException e) {
17. e.printStackTrace();
18. }finally{
19. rs.close();// 最后还得关闭
20. pool.putTable(table); //实际应用过程中，pool获取实例的方式应该抽取为单例模式的，不应在每个方法都重新获取一次(单例明白？就是抽取到专门获取pool的逻辑类中，具体逻辑为如果pool存在着直接使用，如果不存在则new)
21. }
22. }