Java开发Hbase示例

使用Hbase操作数据

  1. package com.sunteng.clickidc.test;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import org.apache.hadoop.conf.Configuration;
  7. import org.apache.hadoop.fs.Path;
  8. import org.apache.hadoop.hbase.*;
  9. import org.apache.hadoop.hbase.client.*;
  10. import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
  11. import org.apache.hadoop.hbase.util.Bytes;
  12. /*
  13. * 不需要实现数据库连接池,内置
  14. * MAVEN依赖错误,使用另外的客户端包
  15. * http://blog.sina.com.cn/s/blog_6a67b5c50100zbrx.html
  16. *
  17. * <!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-shaded-client -->
  18. <dependency>
  19. <groupId>org.apache.hbase</groupId>
  20. <artifactId>hbase-shaded-client</artifactId>
  21. <version>1.2.2</version>
  22. <exclusions>
  23. <exclusion>
  24. <groupId>org.slf4j</groupId>
  25. <artifactId>slf4j-log4j12</artifactId>
  26. </exclusion>
  27. </exclusions>
  28. </dependency>
  29. * */
  30. public class HbaseExample {
  31. /*
  32. * 不强制性创建表
  33. *
  34. * @tableName 表名
  35. * @family 列族列表
  36. * @config 配置信息
  37. */
  38. public static void creatTable(String tableName, String[] family, Configuration config) throws Exception {
  39. try (Connection connection = ConnectionFactory.createConnection(config);
  40. Admin admin = connection.getAdmin()) {
  41. HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
  42. for (int i = 0; i < family.length; i++) {
  43. desc.addFamily(new HColumnDescriptor(family[i]));
  44. }
  45. if (admin.tableExists(desc.getTableName())) {
  46. System.out.println("table Exists!");
  47. throw new Exception("table Exists!");
  48. } else {
  49. admin.createTable(desc);
  50. System.out.println("create table Success!");
  51. }
  52. }
  53. }
  54. /*
  55. * 强制性创建表
  56. *
  57. * @tableName 表名
  58. * @family 列族列表
  59. * @config 配置信息
  60. */
  61. public static void creatTableForce(String tableName, String[] family, Configuration config) throws Exception {
  62. try (Connection connection = ConnectionFactory.createConnection(config);
  63. Admin admin = connection.getAdmin()) {
  64. HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
  65. for (int i = 0; i < family.length; i++) {
  66. desc.addFamily(new HColumnDescriptor(family[i]));
  67. }
  68. if (admin.tableExists(desc.getTableName())) {
  69. admin.disableTable(desc.getTableName());
  70. admin.deleteTable(desc.getTableName());
  71. }
  72. admin.createTable(desc);
  73. System.out.println("create table Success!");
  74. }
  75. }
  76. /*
  77. * 删表
  78. * @tableName 表名
  79. * @config 配置信息
  80. *
  81. */
  82. public static void deleteTable(String tableName, Configuration config) throws Exception {
  83. try (Connection connection = ConnectionFactory.createConnection(config);
  84. Admin admin = connection.getAdmin()) {
  85. TableName tn = TableName.valueOf(tableName);
  86. if (admin.tableExists(tn)) {
  87. admin.disableTable(tn);
  88. admin.deleteTable(tn);
  89. }
  90. }
  91. }
  92. /*
  93. * 查看已有表
  94. *
  95. * @config 配置信息
  96. *
  97. */
  98. public static HTableDescriptor[] listTables(Configuration config) throws IOException {
  99. try (Connection connection = ConnectionFactory.createConnection(config);
  100. Admin admin = connection.getAdmin()) {
  101. HTableDescriptor hTableDescriptors[] = admin.listTables();
  102. return hTableDescriptors;
  103. }
  104. }
  105. /*
  106. * 插入数据
  107. *
  108. * @tableName 表名
  109. * @config 配置信息
  110. * @rowkey 行key
  111. * @colFamily 列族
  112. * @col 子列
  113. * @val 值
  114. *
  115. * */
  116. public static void instertRow(String tableName, Configuration config, String rowkey, String colFamily, String col, String val) throws Exception {
  117. try (Connection connection = ConnectionFactory.createConnection(config)) {
  118. Table table = connection.getTable(TableName.valueOf(tableName));
  119. Put put = new Put(Bytes.toBytes(rowkey));
  120. put.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col), Bytes.toBytes(val));
  121. table.put(put);
  122. //批量插入
  123. /* List<Put> putList = new ArrayList<Put>();
  124. puts.add(put);
  125. table.put(putList);*/
  126. table.close();
  127. System.out.printf("adding success!!Table:%s,Row:%s,Column=%s:%s,Value=%s\n", tableName, rowkey, colFamily, col, val);
  128. }
  129. }
  130. /*
  131. * 删除数据
  132. *
  133. * @tableName 表名
  134. * @config 配置信息
  135. * @rowkey 行key
  136. * @colFamily 列族
  137. * @col 子列
  138. *
  139. * */
  140. public static void deleRow(String tableName, Configuration config, String rowkey, String colFamily, String col) throws Exception {
  141. try (Connection connection = ConnectionFactory.createConnection(config)) {
  142. Table table = connection.getTable(TableName.valueOf(tableName));
  143. Delete delete = new Delete(Bytes.toBytes(rowkey));
  144. //删除指定列族
  145. if (colFamily != null && col == null)
  146. delete.addFamily(Bytes.toBytes(colFamily));
  147. //删除指定列
  148. if (colFamily != null && col != null)
  149. delete.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
  150. table.delete(delete);
  151. //批量删除
  152. /* List<Delete> deleteList = new ArrayList<Delete>();
  153. deleteList.add(delete);
  154. table.delete(deleteList);*/
  155. table.close();
  156. }
  157. }
  158. public static void deleRow(String tableName, Configuration config, String rowkey, String colFamily) throws Exception {
  159. deleRow(tableName, config, rowkey, colFamily, null);
  160. }
  161. public static void deleRow(String tableName, Configuration config, String rowkey) throws Exception {
  162. deleRow(tableName, config, rowkey, null, null);
  163. }
  164. /*
  165. * 根据rowkey查找数据
  166. *
  167. * @tableName 表名
  168. * @config 配置信息
  169. * @rowkey 行key
  170. * @colFamily 列族
  171. * @col 子列
  172. *
  173. * */
  174. public static Result getData(String tableName, Configuration config, String rowkey, String colFamily, String col) throws Exception {
  175. try (Connection connection = ConnectionFactory.createConnection(config)) {
  176. Table table = connection.getTable(TableName.valueOf(tableName));
  177. Get get = new Get(Bytes.toBytes(rowkey));
  178. if (colFamily != null && col == null)
  179. get.addFamily(Bytes.toBytes(colFamily));
  180. if (colFamily != null && col != null)
  181. get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
  182. Result result = table.get(get);
  183. table.close();
  184. return result;
  185. }
  186. }
  187. public static Result getData(String tableName, Configuration config, String rowkey, String colFamily) throws Exception {
  188. return getData(tableName, config, rowkey, colFamily, null);
  189. }
  190. public static Result getData(String tableName, Configuration config, String rowkey) throws Exception {
  191. return getData(tableName, config, rowkey, null, null);
  192. }
  193. /*
  194. * 批量查找数据
  195. * @table 表名
  196. * @config配置文件
  197. * @startRow 开始的行key
  198. * @stopRow 停止的行key
  199. *
  200. * hbase会将自己的元素按照key的ASCII码排序
  201. * 找出5193开头的元素
  202. *
  203. * 5193:1
  204. * 5193:2
  205. * 5194:1
  206. * 51939:1
  207. * 51942:1
  208. *
  209. * scan.setStartRow("5193:#");
  210. * scan.setStopRow("5193::");
  211. *
  212. * 原因:ASCII排序中:"#" < "0-9" < ":"
  213. * 取出来的将是5193:后面跟着数字的元素
  214. * */
  215. public static List<Result> scanData(String tableName, Configuration config, String startRow, String stopRow, int limit) throws Exception {
  216. try (Connection connection = ConnectionFactory.createConnection(config)) {
  217. Table table = connection.getTable(TableName.valueOf(tableName));
  218. Scan scan = new Scan();
  219. if (startRow != null && stopRow != null) {
  220. scan.setStartRow(Bytes.toBytes(startRow));
  221. scan.setStopRow(Bytes.toBytes(stopRow));
  222. }
  223. scan.setBatch(limit);
  224. List<Result> result = new ArrayList<Result>();
  225. ResultScanner resultScanner = table.getScanner(scan);
  226. for (Result r : resultScanner) {
  227. result.add(r);
  228. }
  229. table.close();
  230. return result;
  231. }
  232. }
  233. public static List<Result> scanData(String tableName, Configuration config, int limit) throws Exception {
  234. return scanData(tableName, config, null, null, limit);
  235. }
  236. /*
  237. * 打印表
  238. * @tables 打印的表描述对象
  239. *
  240. * */
  241. public static void printTables(HTableDescriptor[] tables) {
  242. for (HTableDescriptor t : tables) {
  243. HColumnDescriptor[] columns = t.getColumnFamilies();
  244. System.out.printf("tables:%s,columns-family:\n", t.getTableName());
  245. for (HColumnDescriptor column : columns) {
  246. System.out.printf("\t%s\n", column.getNameAsString());
  247. }
  248. }
  249. }
  250. /*
  251. * 格式化输出
  252. * @result 结果
  253. *
  254. * */
  255. public static void showCell(Result result) {
  256. Cell[] cells = result.rawCells();
  257. for (Cell cell : cells) {
  258. System.out.println("RowName:" + new String(CellUtil.cloneRow(cell)) + " ");
  259. System.out.println("Timetamp:" + cell.getTimestamp() + " ");
  260. System.out.println("column Family:" + new String(CellUtil.cloneFamily(cell)) + " ");
  261. System.out.println("row Name:" + new String(CellUtil.cloneQualifier(cell)) + " ");
  262. System.out.println("value:" + new String(CellUtil.cloneValue(cell)) + " ");
  263. System.out.println("---------------");
  264. }
  265. }
  266. public static void main(String... args) {
  267. Configuration config = HBaseConfiguration.create();
  268. config.set("hbase.zookeeper.property.clientPort", "2181");
  269. config.set("hbase.zookeeper.quorum", "192.168.11.73");
  270. config.set("hbase.master", "192.168.11.73:60000");
  271. String tablename = "visitor";
  272. String[] column_family = {"value"};
  273. try {
  274. //创建表
  275. // creatTableForce(tablename, column_family, config);
  276. //列出表信息
  277. HTableDescriptor[] tables = listTables(config);
  278. printTables(tables);
  279. //插入行
  280. for (int i = 1; i < 5; i++)
  281. instertRow(tablename, config, "row1", column_family[0], i + "", "value");
  282. //获取单行值
  283. Result result = getData(tablename, config, "row1", column_family[0]);
  284. showCell(result);
  285. //扫描表,获取前20行
  286. List<Result> results = scanData(tablename, config, 20);
  287. for (Result r : results) {
  288. showCell(r);
  289. }
  290. } catch (Exception e) {
  291. e.printStackTrace();
  292. }
  293. }
  294. }

Java开发Hbase示例的更多相关文章

  1. Java开发工具IntelliJ IDEA创建Andriod项目示例说明

    IntelliJ IDEA社区版作为一个轻量级的Java开发IDE,是一个开箱即用的Android开发工具. 注意:在本次的教程中我们将以Android平台2.2为例进行IntelliJ IDEA的使 ...

  2. 304902阿里巴巴Java开发手册1.4.0

    转自官网 前言 <阿里巴巴Java开发手册>是阿里巴巴集团技术团队的集体智慧结晶和经验总结,经历了多次大规模一线实战的检验及不断完善,系统化地整理成册,回馈给广大开发者.现代软件行业的高速 ...

  3. 阿里巴巴 Java 开发手册 1.4.0

    一.编程规约(一) 命名风格1. [强制]代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束.反例: _name / __name / $name / name_ / name$ ...

  4. JAVA开发手册-Markdown

    前言 前 言 <Java 开发手册>是技术团队的集体智慧结晶和经验总结,经历了多次大规模一线实战的检验及不断完善.现代软件行业的高速发展对开发者的综合素质要求越来越高,因为不仅是编程知识点 ...

  5. 如何自学 Java 开发

    如何自学 Java 开发? 568赞同反对,不会显示你的姓名 李艾米IT路上学习 568 人赞同 Java Web前端技术 HTML 入门视频课程 1 HTML 简介 2 HTML基本结构[ 3 HT ...

  6. Unit01: JAVA开发环境案例

    Top JAVA Fundamental DAY01 JDK及Eclipse目录结构操作 JDK的安装及配置 控制台版的JAVA HelloWorld 使用Eclipse开发Java应用程序 1 JD ...

  7. JAVA开发相关

    JAVA开发相关1. IntelliJ IDEA开发工具熟练使用2. Maven3. Spring框架(IoC.AOP) 1)数据库相关MyBatis 2)数据库连接池 3)事务.多数据源.跨数据库分 ...

  8. JAVA开发工具eclipse中@author怎么改

    1:JAVA开发工具eclipse中@author怎么改,开发的时候为了注明版权信息. 用eclipse开发工具默认的是系统用户,那么怎么修改呢 示例如图所示 首先打开Eclipse--->然后 ...

  9. 面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序

    面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序 Ajax 为更好的 Web 应用程序铺平了道路 在 Web 应用程序开发中,页面重载循环是最大的一个使用障碍,对于 Java™ ...

随机推荐

  1. centos和windows添加路由命令记录

    # 默认路由做香港出口route add default gw 192.168.10.33route add default gw 192.168.10.1 # 删除默认路由# route del d ...

  2. 003-结构型-07-享元模式(Flyweight)

    一.概述 提供了减少对象数且从而改善应用所需的对象结构的方式.运用共享技术有效地支持大是细粒度的对象. 它通过与其他类似对象共享数据来减小内存占用.它使用共享物件,用来尽可能减少内存使用量以及分享资讯 ...

  3. spring-data-redis数据类型

    一.引入依赖 <!-- 缓存 --> <dependency> <groupId>redis.clients</groupId> <artifac ...

  4. SeetaFaceDetection识别人脸

    SeetaFaceDetection识别人脸 #pragma warning(disable: 4819) #include <seeta/FaceEngine.h> #include & ...

  5. k8s记录-ca证书制作(二)

    1)下载cfssl #!/bin/bash wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 wget https://pkg.cfssl.org/R ...

  6. (十四)访问标志 Access_flags

    一.概念 上一章节讲到了常量池,如下图,常量池之后便是访问标志acess_flags,占2个字节(u2). 二.例子 编写一个接口. public interface Test{ public fin ...

  7. iOS扩大按钮的点击范围

    // 重写此方法将按钮的点击范围扩大 - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { CGRect bounds = s ...

  8. yaml中使用harbor

    1.在harbor的ui界面上注册一个账号 姓名:zihao 全名:zhuzihao 密码:Zihao@5tgb 邮箱:15613691030@163.com 2.在需要下载镜像的机器上,同样需要修改 ...

  9. LODOP打印table超宽用省略号带'-'的内容换行问题

    前面的博文有div超宽隐藏(LODOP打印超过后隐藏内容样式),还有有table设置超宽隐藏(),此外,还有超宽后用省略号表示的css样式,此文是针对这个样式的.该样式正常情况下没问题,但是遇到-短线 ...

  10. jQuery调用WebService返回JSON数据

    相信大家都比较了解JSON格式的数据对于ajax的方便,不了解的可以从网上找一下这方面的资料来看一下,这里就不多说了,不清楚的可以在网上查一下,这里只说一下因为参数设置不当引起的取不到返回值的问题. ...