Hbase 建表操作实例源码

       由于最近突然要搞Hbase,以前没搞过,百度了半天,才终于理清了一点头绪,特记录,以备忘。


        实验环境:cdh 5.1.3,首先需要在cdh的安装程序里找到hbase的相关包,把它下载到本地。这里留一个下载地址,百度云盘:cdh5.1.3相关包

 

package com.guet.hbase.util;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
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.util.Bytes;

public class HbaseUtil {

	
	
	public static Configuration configuration;  
	private static HTable table=null;
    static {  
     configuration = HBaseConfiguration.create();  
     configuration.set("hbase.zookeeper.property.clientPort", "2181");  
  configuration.set("hbase.zookeeper.quorum", "192.168.1.62,192.168.1.201,192.168.1.108");  
        configuration.set("hbase.master", "192.168.1.62:600000");  
    } 
    public HbaseUtil(String tableName) throws IOException{
    table = new HTable(configuration,tableName);
	}
	
  //创建表
    public  void createTable(String tableName) {  
         
        try {  
            HBaseAdmin hBaseAdmin = new HBaseAdmin(configuration);  
            if (hBaseAdmin.tableExists(tableName)) {// 如果表已存在,跳过 
               // hBaseAdmin.disableTable(tableName);  
               // hBaseAdmin.deleteTable(tableName);  
                System.out.println(tableName + " is exist,skip...");  
            }  
            
            // 表不存在,就创建表
            else{
           	
 HTableDescriptor tableDescriptor=new HTableDescriptor(tableName.getBytes());  
   tableDescriptor.addFamily(new HColumnDescriptor("cf1"));  //创建列簇1
   tableDescriptor.addFamily(new HColumnDescriptor("cf2"));  //创建列簇2 
    hBaseAdmin.createTable(tableDescriptor); 
    hBaseAdmin.close();	           	          	
                 System.out.println("create table success!"); 
            }    
           
        } catch (MasterNotRunningException e) {  
            e.printStackTrace();  
        } catch (ZooKeeperConnectionException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        
       
    }  
    // 写入数据
    public  void writeRow(String tableName,String rowKey,String qualifier,String value){
		try{
			             
              Put put = new Put(Bytes.toBytes(rowKey));
	      put.add(Bytes.toBytes("cf1"),//列族
		Bytes.toBytes(qualifier),//列名
		Bytes.toBytes(value));//值
		table.put(put);
				
		}catch (IOException e){
			e.printStackTrace();
		}
	}
    
    
}

完毕



发布了26 篇原创文章 · 获赞 9 · 访问量 6万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览