Java开发Hbase示例
Java开发Hbase示例
使用Hbase操作数据
    package com.sunteng.clickidc.test;
    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.fs.Path;
    import org.apache.hadoop.hbase.*;
    import org.apache.hadoop.hbase.client.*;
    import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
    import org.apache.hadoop.hbase.util.Bytes;
    /*
    * 不需要实现数据库连接池,内置
    * MAVEN依赖错误,使用另外的客户端包
    * http://blog.sina.com.cn/s/blog_6a67b5c50100zbrx.html
    *
    *       <!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-shaded-client -->
            <dependency>
                <groupId>org.apache.hbase</groupId>
                <artifactId>hbase-shaded-client</artifactId>
                <version>1.2.2</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-log4j12</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    * */
    public class HbaseExample {
        /*
         * 不强制性创建表
         *
         * @tableName 表名
         * @family 列族列表
         * @config 配置信息
         */
        public static void creatTable(String tableName, String[] family, Configuration config) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config);
                 Admin admin = connection.getAdmin()) {
                HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
                for (int i = 0; i < family.length; i++) {
                    desc.addFamily(new HColumnDescriptor(family[i]));
                }
                if (admin.tableExists(desc.getTableName())) {
                    System.out.println("table Exists!");
                    throw new Exception("table Exists!");
                } else {
                    admin.createTable(desc);
                    System.out.println("create table Success!");
                }
            }
        }
        /*
         * 强制性创建表
         *
         * @tableName 表名
         * @family 列族列表
         * @config 配置信息
         */
        public static void creatTableForce(String tableName, String[] family, Configuration config) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config);
                 Admin admin = connection.getAdmin()) {
                HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
                for (int i = 0; i < family.length; i++) {
                    desc.addFamily(new HColumnDescriptor(family[i]));
                }
                if (admin.tableExists(desc.getTableName())) {
                    admin.disableTable(desc.getTableName());
                    admin.deleteTable(desc.getTableName());
                }
                admin.createTable(desc);
                System.out.println("create table Success!");
            }
        }
        /*
         *  删表
         *  @tableName 表名
         *  @config 配置信息
         *
         */
        public static void deleteTable(String tableName, Configuration config) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config);
                 Admin admin = connection.getAdmin()) {
                TableName tn = TableName.valueOf(tableName);
                if (admin.tableExists(tn)) {
                    admin.disableTable(tn);
                    admin.deleteTable(tn);
                }
            }
        }
        /*
        * 查看已有表
        *
        * @config 配置信息
        *
        */
        public static HTableDescriptor[] listTables(Configuration config) throws IOException {
            try (Connection connection = ConnectionFactory.createConnection(config);
                 Admin admin = connection.getAdmin()) {
                HTableDescriptor hTableDescriptors[] = admin.listTables();
                return hTableDescriptors;
            }
        }
        /*
        * 插入数据
        *
        * @tableName 表名
        * @config 配置信息
        * @rowkey 行key
        * @colFamily 列族
        * @col 子列
        * @val 值
        *
        * */
        public static void instertRow(String tableName, Configuration config, String rowkey, String colFamily, String col, String val) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config)) {
                Table table = connection.getTable(TableName.valueOf(tableName));
                Put put = new Put(Bytes.toBytes(rowkey));
                put.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col), Bytes.toBytes(val));
                table.put(put);
                //批量插入
               /* List<Put> putList = new ArrayList<Put>();
                puts.add(put);
                table.put(putList);*/
                table.close();
                System.out.printf("adding success!!Table:%s,Row:%s,Column=%s:%s,Value=%s\n", tableName, rowkey, colFamily, col, val);
            }
        }
        /*
        * 删除数据
        *
        * @tableName 表名
        * @config 配置信息
        * @rowkey 行key
        * @colFamily 列族
        * @col 子列
        *
        * */
        public static void deleRow(String tableName, Configuration config, String rowkey, String colFamily, String col) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config)) {
                Table table = connection.getTable(TableName.valueOf(tableName));
                Delete delete = new Delete(Bytes.toBytes(rowkey));
                //删除指定列族
                if (colFamily != null && col == null)
                    delete.addFamily(Bytes.toBytes(colFamily));
                //删除指定列
                if (colFamily != null && col != null)
                    delete.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
                table.delete(delete);
                //批量删除
               /* List<Delete> deleteList = new ArrayList<Delete>();
                deleteList.add(delete);
                table.delete(deleteList);*/
                table.close();
            }
        }
        public static void deleRow(String tableName, Configuration config, String rowkey, String colFamily) throws Exception {
            deleRow(tableName, config, rowkey, colFamily, null);
        }
        public static void deleRow(String tableName, Configuration config, String rowkey) throws Exception {
            deleRow(tableName, config, rowkey, null, null);
        }
        /*
        * 根据rowkey查找数据
        *
        * @tableName 表名
        * @config 配置信息
        * @rowkey 行key
        * @colFamily 列族
        * @col 子列
        *
        * */
        public static Result getData(String tableName, Configuration config, String rowkey, String colFamily, String col) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config)) {
                Table table = connection.getTable(TableName.valueOf(tableName));
                Get get = new Get(Bytes.toBytes(rowkey));
                if (colFamily != null && col == null)
                    get.addFamily(Bytes.toBytes(colFamily));
                if (colFamily != null && col != null)
                    get.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(col));
                Result result = table.get(get);
                table.close();
                return result;
            }
        }
        public static Result getData(String tableName, Configuration config, String rowkey, String colFamily) throws Exception {
            return getData(tableName, config, rowkey, colFamily, null);
        }
        public static Result getData(String tableName, Configuration config, String rowkey) throws Exception {
            return getData(tableName, config, rowkey, null, null);
        }
        /*
        * 批量查找数据
        * @table 表名
        * @config配置文件
        * @startRow 开始的行key
        * @stopRow 停止的行key
        *
        * hbase会将自己的元素按照key的ASCII码排序
        * 找出5193开头的元素
        *
        *   5193:1
        *   5193:2
        *   5194:1
        *   51939:1
        *   51942:1
        *
        *  scan.setStartRow("5193:#");
        *  scan.setStopRow("5193::");
        *
        *  原因:ASCII排序中:"#" < "0-9" < ":"
        *  取出来的将是5193:后面跟着数字的元素
        * */
        public static List<Result> scanData(String tableName, Configuration config, String startRow, String stopRow, int limit) throws Exception {
            try (Connection connection = ConnectionFactory.createConnection(config)) {
                Table table = connection.getTable(TableName.valueOf(tableName));
                Scan scan = new Scan();
                if (startRow != null && stopRow != null) {
                    scan.setStartRow(Bytes.toBytes(startRow));
                    scan.setStopRow(Bytes.toBytes(stopRow));
                }
                scan.setBatch(limit);
                List<Result> result = new ArrayList<Result>();
                ResultScanner resultScanner = table.getScanner(scan);
                for (Result r : resultScanner) {
                    result.add(r);
                }
                table.close();
                return result;
            }
        }
        public static List<Result> scanData(String tableName, Configuration config, int limit) throws Exception {
            return scanData(tableName, config, null, null, limit);
        }
        /*
        * 打印表
        * @tables 打印的表描述对象
        *
        * */
        public static void printTables(HTableDescriptor[] tables) {
            for (HTableDescriptor t : tables) {
                HColumnDescriptor[] columns = t.getColumnFamilies();
                System.out.printf("tables:%s,columns-family:\n", t.getTableName());
                for (HColumnDescriptor column : columns) {
                    System.out.printf("\t%s\n", column.getNameAsString());
                }
            }
        }
        /*
         * 格式化输出
         * @result 结果
         *
         * */
        public static void showCell(Result result) {
            Cell[] cells = result.rawCells();
            for (Cell cell : cells) {
                System.out.println("RowName:" + new String(CellUtil.cloneRow(cell)) + " ");
                System.out.println("Timetamp:" + cell.getTimestamp() + " ");
                System.out.println("column Family:" + new String(CellUtil.cloneFamily(cell)) + " ");
                System.out.println("row Name:" + new String(CellUtil.cloneQualifier(cell)) + " ");
                System.out.println("value:" + new String(CellUtil.cloneValue(cell)) + " ");
                System.out.println("---------------");
            }
        }
        public static void main(String... args) {
            Configuration config = HBaseConfiguration.create();
            config.set("hbase.zookeeper.property.clientPort", "2181");
            config.set("hbase.zookeeper.quorum", "192.168.11.73");
            config.set("hbase.master", "192.168.11.73:60000");
            String tablename = "visitor";
            String[] column_family = {"value"};
            try {
                //创建表
    //          creatTableForce(tablename, column_family, config);
                //列出表信息
                HTableDescriptor[] tables = listTables(config);
                printTables(tables);
                //插入行
                for (int i = 1; i < 5; i++)
                    instertRow(tablename, config, "row1", column_family[0], i + "", "value");
                //获取单行值
                Result result = getData(tablename, config, "row1", column_family[0]);
                showCell(result);
                //扫描表,获取前20行
                List<Result> results = scanData(tablename, config, 20);
                for (Result r : results) {
                    showCell(r);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
												
											Java开发Hbase示例的更多相关文章
- Java开发工具IntelliJ IDEA创建Andriod项目示例说明
		
IntelliJ IDEA社区版作为一个轻量级的Java开发IDE,是一个开箱即用的Android开发工具. 注意:在本次的教程中我们将以Android平台2.2为例进行IntelliJ IDEA的使 ...
 - 304902阿里巴巴Java开发手册1.4.0
		
转自官网 前言 <阿里巴巴Java开发手册>是阿里巴巴集团技术团队的集体智慧结晶和经验总结,经历了多次大规模一线实战的检验及不断完善,系统化地整理成册,回馈给广大开发者.现代软件行业的高速 ...
 - 阿里巴巴 Java 开发手册 1.4.0
		
一.编程规约(一) 命名风格1. [强制]代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束.反例: _name / __name / $name / name_ / name$ ...
 - JAVA开发手册-Markdown
		
前言 前 言 <Java 开发手册>是技术团队的集体智慧结晶和经验总结,经历了多次大规模一线实战的检验及不断完善.现代软件行业的高速发展对开发者的综合素质要求越来越高,因为不仅是编程知识点 ...
 - 如何自学 Java 开发
		
如何自学 Java 开发? 568赞同反对,不会显示你的姓名 李艾米IT路上学习 568 人赞同 Java Web前端技术 HTML 入门视频课程 1 HTML 简介 2 HTML基本结构[ 3 HT ...
 - Unit01: JAVA开发环境案例
		
Top JAVA Fundamental DAY01 JDK及Eclipse目录结构操作 JDK的安装及配置 控制台版的JAVA HelloWorld 使用Eclipse开发Java应用程序 1 JD ...
 - JAVA开发相关
		
JAVA开发相关1. IntelliJ IDEA开发工具熟练使用2. Maven3. Spring框架(IoC.AOP) 1)数据库相关MyBatis 2)数据库连接池 3)事务.多数据源.跨数据库分 ...
 - JAVA开发工具eclipse中@author怎么改
		
1:JAVA开发工具eclipse中@author怎么改,开发的时候为了注明版权信息. 用eclipse开发工具默认的是系统用户,那么怎么修改呢 示例如图所示 首先打开Eclipse--->然后 ...
 - 面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序
		
面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序 Ajax 为更好的 Web 应用程序铺平了道路 在 Web 应用程序开发中,页面重载循环是最大的一个使用障碍,对于 Java™ ...
 
随机推荐
- iTop汉化
 - 干货满满!10分钟看懂Docker和K8S(转)
			
2010年,几个搞IT的年轻人,在美国旧金山成立了一家名叫“dotCloud”的公司. 这家公司主要提供基于PaaS的云计算技术服务.具体来说,是和LXC有关的容器技术. LXC,就是Linux容器虚 ...
 - PHP使用MongoDB类操作MongoDB数据库总结
			
参考:https://www.php.net/manual/zh/class.mongodb-driver-manager.php 参考:https://www.zhaokeli.com/articl ...
 - Dart泛型
			
/* 通俗理解:泛型就是解决 类 接口 方法的复用性.以及对不特定数据类型的支持(类型校验) */ //只能返回string类型的数据 // String getData(String value){ ...
 - 006-guava 集合-集合工具类-集合扩展工具类
			
一.概述 需要实现自己的集合扩展.也许你想要在元素被添加到列表时增加特定的行为,或者你想实现一个Iterable,其底层实际上是遍历数据库查询的结果集 二.使用 2.1.ForwardingList装 ...
 - Eclipse | 如何修改web项目的访问链接名,项目名
			
转: Eclipse | 如何修改web项目的访问链接名,项目名 2018-01-04 17:52:05 Mandsence 阅读数 2180更多 分类专栏: 其他 版权声明:本文为博主原创文章, ...
 - Python - Django - 组件
			
网站中通常会有一个导航条,如下图 这个导航条在很多页面都会存在 可以把导航条做成一个组件,让要显示导航条的网页包含 导航条组件 nav.html: <h1>假装这是一个导航条</h1 ...
 - 压力测试 Apache ab
			
https://www.jianshu.com/p/166a4ea8aade https://httpd.apache.org/docs/2.4/programs/ab.html 安装: 按照提示安装 ...
 - 使用JSQLParser解析SQL中涉及到的表
			
首先添加Maven依赖: <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId& ...
 - PNG压缩工具-PNGGauntlet
			
PNGGauntlet下载地址 对于前端来说非常实用的PNG压缩软件,支持拖拽,就是软件速度比较慢.