大數據學習系列之三 ----- HBase Java Api 圖文詳解


引言

在上一篇中大數據學習系列之二 ----- HBase環境搭建(單機) 中,成功搭建了Hadoop+HBase的環境,本文則主要講述使用Java 對HBase的一些操作。

一、事前准備

1.確認hadoop和hbase成功啟動

這里寫圖片描述

2.確認防火牆是否關閉

3.maven所需要的依賴架包

<!--hadoop 相關架包 -->
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-common</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-client</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-hdfs</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-mapreduce-client-core</artifactId>
			<version>2.8.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hadoop</groupId>
			<artifactId>hadoop-yarn-common</artifactId>
			<version>2.8.2</version>
		</dependency>

<!--HBase相關jar -->
		<dependency>
			<groupId>org.apache.hbase</groupId>
			<artifactId>hbase-hadoop-compat</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.hbase</groupId>
			<artifactId>hbase-server</artifactId>
			<version>1.1.2</version>
		</dependency>
<dependency>
			<groupId>org.apache.hbase</groupId>
			<artifactId>hbase-client</artifactId>
			<version>1.1.2</version>
		</dependency>
<dependency>
			<groupId>org.apache.hbase</groupId>
		    <artifactId>hbase-common</artifactId>
	        <version>1.1.2</version>
	    </dependency>

4.修改hosts文件(可選)

修改Windows C:\Windows\System32\drivers\etc 目錄下的hosts文件,添加hbase的主機ip和主機名做關系映射。

192.168.238.128 master

注:如果不使用映射,那么將代碼中的主機名改成IP即可。

5.HBase的原理

這篇文章介紹得很詳細:
http://blog.csdn.net/woshiwanxin102213/article/details/17584043

二、測試示例

1.創建表

創建兩張表 t_student、t_student_info 這兩張表,並添加兩個列族
創建成功之后可以在 hbase shell和16010界面中看到。這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

2.添加數據

成功創建表之后,在這兩張表中插入數據。
因為HBase是動態數據庫,所以列是可以新增的。
HBase的新增和修改是一個方法,數據相同的,后來的數據會將前面的覆蓋掉!
這里寫圖片描述

這里寫圖片描述

3.查詢數據

分別根據表名、行健、列族、列來查詢
這里寫圖片描述

4.刪除數據

刪除其中的一條數據
這里寫圖片描述

三、代碼示例

工具類

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
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.util.Bytes;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * Title: HBaseUtil
 * Description: HBase工具類 
 * Version:1.0.0
 * @author pancm
 * @date 2017年12月6日
 */
public class HBaseUtil {
	/** hadoop 連接 */
	private static Configuration conf = null;
	/** hbase 連接 */
	private static Connection con = null;
	/** 會話 */
	private static Admin admin = null;

	private static String ip ="master";
    private static String port ="2181";
    private static String port1 ="9001";
	   
   // 初始化連接
   static {
	   // 獲得配制文件對象
       conf = HBaseConfiguration.create(); 
       // 設置配置參數
		conf.set("hbase.zookeeper.quorum", ip);
		conf.set("hbase.zookeeper.property.clientPort", port);  
		//如果hbase是集群,這個必須加上 
		//這個ip和端口是在hadoop/mapred-site.xml配置文件配置的
		conf.set("hbase.master", ip+":"+port1); 
   }
		

	/**
	 * 獲取連接
	 * 
	 * @return
	 */
	public synchronized static Connection getConnection() {
		try {
			if (null == con || con.isClosed()) {
				// 獲得連接對象
				con = ConnectionFactory.createConnection(conf);
			}
		} catch (IOException e) {
			System.out.println("獲取連接失敗!");
			e.printStackTrace();
		}

		return con;
	}

	/**
	 * 連接關閉
	 */
	public static void close() {
		try {
			if (admin != null) {
				admin.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (IOException e) {
			System.out.println("連接關閉失敗!");
			e.printStackTrace();
		}
	}

	/**
	 * 創建表
	 * 
	 * @param tableName
	 *            表名
	 * @param columnFamily
	 *            列族
	 */
	public static void creatTable(String tableName, String[] columnFamily) {
		if(null==tableName||tableName.length()==0){
			return;
		}
		if(null==columnFamily||columnFamily.length==0){
			return;
		}
		// 創建表名對象
		TableName tn = TableName.valueOf(tableName);
		// a.判斷數據庫是否存在
		try {
			// 獲取會話
			admin = getConnection().getAdmin();
			if (admin.tableExists(tn)) {
				System.out.println(tableName + " 表存在,刪除表....");
				// 先使表設置為不可編輯
				admin.disableTable(tn);
				// 刪除表
				admin.deleteTable(tn);
				System.out.println("表刪除成功.....");
			}
			// 創建表結構對象
			HTableDescriptor htd = new HTableDescriptor(tn);
			for (String str : columnFamily) {
				// 創建列族結構對象
				HColumnDescriptor hcd = new HColumnDescriptor(str);
				htd.addFamily(hcd);
			}
			// 創建表
			admin.createTable(htd);
			System.out.println(tableName + " 表創建成功!");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}

	/**
	 * 數據單條插入或更新
	 * 
	 * @param tableName
	 *            表名
	 * @param rowKey
	 *            行健 (主鍵)
	 * @param family
	 *            列族
	 * @param qualifier
	 *            列
	 * @param value
	 *            存入的值
	 * @return
	 */
	public static void insert(String tableName, String rowKey, String family,
			String qualifier, String value) {
		Table t = null;
		try {
			t = getConnection().getTable(TableName.valueOf(tableName));
			Put put = new Put(Bytes.toBytes(rowKey));
			put.addColumn(Bytes.toBytes(family), Bytes.toBytes(qualifier),
					Bytes.toBytes(value));
			t.put(put);
			System.out.println(tableName + " 更新成功!");
		} catch (IOException e) {
			System.out.println(tableName + " 更新失敗!");
			e.printStackTrace();
		} finally {
			close();
		}
	}

	/**
	 * 數據批量插入或更新
	 * 
	 * @param tableName
	 *            表名
	 * @param list
	 *            hbase的數據 
	 * @return
	 */
	public static void insertBatch(String tableName, List<?> list) {
		if (null == tableName ||tableName.length()==0) {
			return;
		}
		if( null == list || list.size() == 0){
			return;
		}
		Table t = null;
		Put put = null;
		JSONObject json = null;
		List<Put> puts = new ArrayList<Put>();
		try {
			t = getConnection().getTable(TableName.valueOf(tableName));
			for (int i = 0, j = list.size(); i < j; i++) {
				json = (JSONObject) list.get(i);
				put = new Put(Bytes.toBytes(json.getString("rowKey")));
				put.addColumn(Bytes.toBytes(json.getString("family")),
						Bytes.toBytes(json.getString("qualifier")),
						Bytes.toBytes(json.getString("value")));
				puts.add(put);
			}
			t.put(puts);
			System.out.println(tableName + " 更新成功!");
		} catch (IOException e) {
			System.out.println(tableName + " 更新失敗!");
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	/**
	 * 數據刪除 
	 * @param tableName 表名
	 * @param rowKey	行健
	 * @return
	 */
    public static void delete(String tableName, String rowKey) {
    	delete(tableName,rowKey,"","");
    }
	
	/**
	 * 數據刪除 
	 * @param tableName 表名
	 * @param rowKey	行健
	 * @param family	列族
	 * @return
	 */
    public static void delete(String tableName, String rowKey, String family) {
    	delete(tableName,rowKey,family,"");
    }
	
	/**
	 * 數據刪除 
	 * @param tableName 表名
	 * @param rowKey	行健
	 * @param family	列族
	 * @param qualifier 列
	 * @return
	 */
    public static void delete(String tableName, String rowKey, String family,
            String qualifier) {
    	if (null == tableName ||tableName.length()==0) {
			return;
		}
		if( null == rowKey || rowKey.length() == 0){
			return;
		}
    	Table t = null;
        try {
            t = getConnection().getTable(TableName.valueOf(tableName));
            Delete del = new Delete(Bytes.toBytes(rowKey));
            // 如果列族不為空
 			if (null != family && family.length() > 0) {
 				// 如果列不為空
 				if (null != qualifier && qualifier.length() > 0) {
 					del.addColumn(Bytes.toBytes(family),
 							Bytes.toBytes(qualifier));
 				} else {
 					del.addFamily(Bytes.toBytes(family));
 				}
 			}      
            t.delete(del);    
        } catch (IOException e) {
        	System.out.println("刪除失敗!");
            e.printStackTrace();
        } finally {
          close();
        }
    }
	
	/**
	 * 查詢該表中的所有數據
	 * 
	 * @param tableName
	 *            表名
	 */
	public static void select(String tableName) {
		if(null==tableName||tableName.length()==0){
			return;
		}
		Table t = null;
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		try {
			t = getConnection().getTable(TableName.valueOf(tableName));
			// 讀取操作
			Scan scan = new Scan();
			// 得到掃描的結果集
			ResultScanner rs = t.getScanner(scan);
			if (null == rs ) {
				return;
			}
			for (Result result : rs) {
				// 得到單元格集合
				List<Cell> cs = result.listCells();
				if (null == cs || cs.size() == 0) {
					continue;
				}
				for (Cell cell : cs) {
					Map<String,Object> map=new HashMap<String, Object>();
					map.put("rowKey", Bytes.toString(CellUtil.cloneRow(cell)));// 取行健
					map.put("timestamp", cell.getTimestamp());// 取到時間戳
					map.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));// 取到列族
					map.put("qualifier", Bytes.toString(CellUtil.cloneQualifier(cell)));// 取到列
					map.put("value", Bytes.toString(CellUtil.cloneValue(cell)));// 取到值
					list.add(map);
				}
			}
			System.out.println("查詢的數據:"+list);
		} catch (IOException e) {
			System.out.println("查詢失敗!");
			e.printStackTrace();
		} finally {
			close();
		}
	}

	/**
	 * 根據表名和行健查詢
	 * @param tableName
	 * @param rowKey
	 */
	public static void select(String tableName, String rowKey) {
		select(tableName,rowKey,"","");
	}
	
	/**
	 * 根據表名、行健和列族查詢
	 * @param tableName
	 * @param rowKey
	 * @param family
	 */
	public static void select(String tableName, String rowKey, String family) {
		select(tableName,rowKey,family,"");
	}
	
	/**
	 * 根據條件明細查詢
	 * 
	 * @param tableName
	 *            表名
	 * @param rowKey
	 *            行健 (主鍵)
	 * @param family
	 *            列族
	 * @param qualifier
	 *            列
	 */
	public static void select(String tableName, String rowKey, String family,
			String qualifier) {
		Table t = null;
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		try {
			t = getConnection().getTable(TableName.valueOf(tableName));
			// 通過HBase中的 get來進行查詢
			Get get = new Get(Bytes.toBytes(rowKey));
			// 如果列族不為空
			if (null != family && family.length() > 0) {
				// 如果列不為空
				if (null != qualifier && qualifier.length() > 0) {
					get.addColumn(Bytes.toBytes(family),
							Bytes.toBytes(qualifier));
				} else {
					get.addFamily(Bytes.toBytes(family));
				}
			}
			Result r = t.get(get);
			List<Cell> cs = r.listCells();
			if (null == cs || cs.size() == 0) {
				return;
			}
			for (Cell cell : cs) {
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("rowKey", Bytes.toString(CellUtil.cloneRow(cell)));// 取行健
				map.put("timestamp", cell.getTimestamp());// 取到時間戳
				map.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));// 取到列族
				map.put("qualifier", Bytes.toString(CellUtil.cloneQualifier(cell)));// 取到列
				map.put("value", Bytes.toString(CellUtil.cloneValue(cell)));// 取到值
				list.add(map);
			}
			System.out.println("查詢的數據:"+list);
		} catch (IOException e) {
			System.out.println("查詢失敗!");
			e.printStackTrace();
		} finally {
			close();
		}
	}
}

測試代碼

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
/**
 * 
* Title: hbaseTest
* Description: HBase 相關測試
* Version:1.0.0  
* @author pancm
* @date 2017年11月23日
 */
public class hbaseTest {
	
	public static void main(String[] args) {
		test();
	}

	/**
	 * 一些測試
	 */
	private static void test() {
		String tableName1="t_student",tableName2="t_student_info";
		String []columnFamily1={"st1","st2"};
		String []columnFamily2={"stf1","stf2"};
		HBaseUtil.creatTable(tableName1, columnFamily1);
		HBaseUtil.creatTable(tableName2, columnFamily2);
		
		HBaseUtil.insert(tableName1, "1001", columnFamily1[0], "name", "zhangsan");
		HBaseUtil.insert(tableName1, "1002", columnFamily1[0], "name", "lisi");
		HBaseUtil.insert(tableName1, "1001", columnFamily1[1], "age", "18");
		HBaseUtil.insert(tableName1, "1002", columnFamily1[1], "age", "20");
		
		HBaseUtil.insert(tableName2, "1001", columnFamily2[0], "phone", "123456");
		HBaseUtil.insert(tableName2, "1002", columnFamily2[0], "phone", "234567");
		HBaseUtil.insert(tableName2, "1001", columnFamily2[1], "mail", "123@163.com");
		HBaseUtil.insert(tableName2, "1002", columnFamily2[1], "mail", "234@163.com");
		
		HBaseUtil.select(tableName1); //查詢該表所有數據
		HBaseUtil.select(tableName1, "1001"); //根據表名和行健查詢
		HBaseUtil.select(tableName2, "1002",columnFamily2[0]); //根據表名、行健和列族查詢
		HBaseUtil.select(tableName2, "1002",columnFamily2[1],"mail"); //根據表名、行健、列族、和列查詢
		
		HBaseUtil.select(tableName1, "1002"); //根據表名和行健查詢
		HBaseUtil.delete(tableName1, "1002", columnFamily1[0]);//刪除數據
		HBaseUtil.select(tableName1, "1002"); //根據表名和行健查詢
		
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM