mavan+Java操作HBase

Hbase作为大数据存储数据库,其写能力非常强,加上Hbase本身就脱胎于Hadoop故和Hadoop的兼容性极好,非常适合于存储半规则数据(灵活、可扩展性强、大数据存储)。基于Hadoop的mapreduce + Hbase存储,非常适合处理大数据。

maven配置:

		<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-common -->
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>2.7.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-common -->
		<dependency>
			<groupId>org.apache.hbase</groupId>
			<artifactId>hbase-common</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
		<dependency>
			<groupId>org.apache.hbase</groupId>
			<artifactId>hbase-client</artifactId>
			<version>1.3.1</version>
		</dependency>


package com.aaron;

import java.io.IOException;
import java.util.ArrayList;
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.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
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.client.Table;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.filter.ValueFilter;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * 连接HBase
 * @Author 指尖上的行者 on 2017年5月19日
 */
public class HBaseDemo {
    // 与HBase数据库的连接对象
    Connection connection;
    // 数据库元数据操作对象
    Admin admin;

    public void setUp() {
    	try {
    		// 取得一个数据库连接的配置参数对象
            Configuration conf = HBaseConfiguration.create();
            // 设置连接参数:HBase数据库所在的主机IP
            conf.set("hbase.zookeeper.quorum", "192.168.56.22,192.168.56.23,192.168.56.24");
            // 设置连接参数:HBase数据库使用的端口
            conf.set("hbase.zookeeper.property.clientPort", "2181");
            conf.set("hbase.master", "192.168.56.22:16020"); 
            
            // 取得一个数据库连接对象
            connection = ConnectionFactory.createConnection(conf);
            // 取得一个数据库元数据操作对象
            admin = connection.getAdmin();
	} catch (Exception e) {
		e.printStackTrace();
	}
    }
    
    public static void main(String[] args) { 
    	HBaseDemo demo=new HBaseDemo();
    	demo.setUp();
    	demo.queryTableByCondition();
    } 

    /**
     * 创建表
     */
    public void createTable() throws IOException{
        System.out.println("---------------创建表 START-----------------");
        // 数据表表名
        String tableNameString = "DM_ALL_INVEST";
        // 新建一个数据表表名对象
        TableName tableName = TableName.valueOf(tableNameString);
        // 如果需要新建的表已经存在
        if(admin.tableExists(tableName)){
            System.out.println("表已经存在!");
        }
        // 如果需要新建的表不存在
        else{
            // 数据表描述对象
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
            // 列族描述对象
            HColumnDescriptor family= new HColumnDescriptor("base");;
            // 在数据表中新建一个列族
            hTableDescriptor.addFamily(family);
            // 新建数据表
            admin.createTable(hTableDescriptor);
        }
        System.out.println("---------------创建表 END-----------------");
    }

    /**
     * 查询整表数据
     */
     
     public void queryTable() throws IOException{
        System.out.println("---------------查询整表数据 START-----------------");
        // 取得数据表对象
        Table table = connection.getTable(TableName.valueOf("DM_ALL_INVEST"));
        // 取得表中所有数据
        ResultScanner scanner = table.getScanner(new Scan());
        // 循环输出表中的数据
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("row key is:" + new String(row));
            List<Cell> listCells = result.listCells();
            for (Cell cell : listCells) {
                byte[] familyArray = cell.getFamilyArray();
                byte[] qualifierArray = cell.getQualifierArray();
                byte[] valueArray = cell.getValueArray();
                System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                             + new String(valueArray));
            }
        }
        System.out.println("---------------查询整表数据 END-----------------");
    }

    /**
     * 按行键查询表数据
     */
     
    public void queryTableByRowKey() throws IOException{
        System.out.println("---------------按行键查询表数据 START-----------------");
        // 取得数据表对象
        Table table = connection.getTable(TableName.valueOf("DM_ALL_INVEST"));
        // 新建一个查询对象作为查询条件
        Get get = new Get("row8".getBytes());
        // 按行键查询数据
        Result result = table.get(get);
        byte[] row = result.getRow();
        System.out.println("row key is:" + new String(row));
        List<Cell> listCells = result.listCells();
        for (Cell cell : listCells) {
            byte[] familyArray = cell.getFamilyArray();
            byte[] qualifierArray = cell.getQualifierArray();
            byte[] valueArray = cell.getValueArray();
            System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) + new String(valueArray));
        }
        System.out.println("---------------按行键查询表数据 END-----------------");
    }

    /**
     * 按条件查询表数据
     */
     
    public void queryTableByCondition(){
    	try {
    		System.out.println("---------------按条件查询表数据 START-----------------");
            // 取得数据表对象
            Table table = connection.getTable(TableName.valueOf("DM_ALL_INVEST"));
            // 创建一个查询过滤器
//            Filter filter = new SingleColumnValueFilter(Bytes.toBytes("base"), //列族
//            											Bytes.toBytes("name"), //列名 
//                                                        CompareOp.EQUAL, Bytes.toBytes("bookName6"));//值
            Filter filter = new ValueFilter(CompareFilter.CompareOp.EQUAL,                     
                    new SubstringComparator("13111111111"));//不需要指定某个列,含指某个值的列的数据都取出来,混在一起 
            // 创建一个数据表扫描器
            Scan scan = new Scan();
            // 将查询过滤器加入到数据表扫描器对象
            scan.setFilter(filter);
            // 执行查询操作,并取得查询结果
            ResultScanner scanner = table.getScanner(scan);
            // 循环输出查询结果
            for (Result result : scanner) {
                byte[] row = result.getRow();
                System.out.println("row key is:" + new String(row));
                List<Cell> listCells = result.listCells();
                for (Cell cell : listCells) {
                    byte[] familyArray = cell.getFamilyArray();
                    byte[] qualifierArray = cell.getQualifierArray();
                    byte[] valueArray = cell.getValueArray();
                    System.out.println("row value is:" + Bytes.toString(familyArray) + Bytes.toString(qualifierArray) + Bytes.toString(valueArray));
                }
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
        System.out.println("---------------按条件查询表数据 END-----------------");
    }

    /**
     * 清空表
     */
    public void truncateTable() throws IOException{
        System.out.println("---------------清空表 START-----------------");
        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("DM_ALL_INVEST");
        // 设置表状态为无效
        admin.disableTable(tableName);
        // 清空指定表的数据
        admin.truncateTable(tableName, true);
        System.out.println("---------------清空表 End-----------------");
    }

    /**
     * 删除表
     */
    public void deleteTable() throws IOException{
        System.out.println("---------------删除表 START-----------------");
        // 设置表状态为无效
        admin.disableTable(TableName.valueOf("DM_ALL_INVEST"));
        // 删除指定的数据表
        admin.deleteTable(TableName.valueOf("DM_ALL_INVEST"));
        System.out.println("---------------删除表 End-----------------");
    }

    /**
     * 删除行
     */
    public void deleteByRowKey() throws IOException{
        System.out.println("---------------删除行 START-----------------");
        // 取得待操作的数据表对象
        Table table = connection.getTable(TableName.valueOf("DM_ALL_INVEST"));
        // 创建删除条件对象
        Delete delete = new Delete(Bytes.toBytes("row2"));
        // 执行删除操作
        table.delete(delete);
        System.out.println("---------------删除行 End-----------------");
    }

    /**
     * 删除行(按条件)
     */
    public void deleteByCondition() throws IOException, DeserializationException{
        System.out.println("---------------删除行(按条件) START-----------------");
        // 步骤1:调用queryTableByCondition()方法取得需要删除的数据列表 
        // 步骤2:循环步骤1的查询结果,对每个结果调用deleteByRowKey()方法
        System.out.println("---------------删除行(按条件) End-----------------");
    }

    /**
     * 新建列族
     */
    public void addColumnFamily() throws IOException{
        System.out.println("---------------新建列族 START-----------------");
        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("DM_ALL_INVEST");
        // 创建列族对象
        HColumnDescriptor columnDescriptor = new HColumnDescriptor("more");
        // 将新创建的列族添加到指定的数据表
        admin.addColumn(tableName, columnDescriptor);
        System.out.println("---------------新建列族 END-----------------");
    }

    /**
     * 删除列族
     */
    public void deleteColumnFamily() throws IOException{
        System.out.println("---------------删除列族 START-----------------");
        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("DM_ALL_INVEST");
        // 删除指定数据表中的指定列族
        admin.deleteColumn(tableName, "more".getBytes());
        System.out.println("---------------删除列族 END-----------------");
    }

    /**
     * 插入数据
     */
    public void insert() throws IOException{
        System.out.println("---------------插入数据 START-----------------");
        // 取得一个数据表对象
        Table table = connection.getTable(TableName.valueOf("DM_ALL_INVEST"));
        // 需要插入数据库的数据集合
        List<Put> putList = new ArrayList<Put>();
        Put put;
        // 生成数据集合
        for(int i = 0; i < 10; i++){
            put = new Put(Bytes.toBytes("row" + i));
            put.addColumn(Bytes.toBytes("base"), Bytes.toBytes("name"), Bytes.toBytes("bookName" + i));

            putList.add(put);
        }
        // 将数据集合插入到数据库
        table.put(putList);
        System.out.println("---------------插入数据 END-----------------");
    }

}

如果运行时出现异常,如下:


则表示未配置HADOOP的环境变量,配置方式有两种,如下:

1、在“高级系统设置”中配置,与配置JDK一致


2、通过代码配置

System.setProperty("hadoop.home.dir", "D:/hadoop-common-2.2.0-bin-master");//配置HADOOP_HOME环境变量


配置完成之后,可以通过如下方式检测是否配置成功:

System.out.println(System.getenv("HADOOP_HOME"));//测试是否可以获取到HADOOP_HOME变量


参考资料:http://blog.csdn.net/qq_31570685/article/details/51757604

hadoop下载地址:http://download.csdn.net/detail/zlb824/9903632

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值