HBase2javaApi接口舉例分析

這篇文章主要介紹“HBase2 java Api接口舉例分析”,在日常操作中,相信很多人在HBase2 java Api接口舉例分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”HBase2 java Api接口舉例分析”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

公司主營業(yè)務(wù):成都網(wǎng)站制作、網(wǎng)站設(shè)計、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。成都創(chuàng)新互聯(lián)是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴(yán)謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。成都創(chuàng)新互聯(lián)推出固鎮(zhèn)免費做網(wǎng)站回饋大家。

接口介紹

攔截器

  • CompareOperator.LESS 匹配小宇設(shè)定值的值

  • CompareOperator.LESS_OR_EQUAL 匹配小宇或等于設(shè)定值的值 

  • CompareOperator.EQUAL 匹配等于設(shè)定值的值 

  • CompareOperator.NOT_EQUAL 匹配與設(shè)定值不相等的值 

  • CompareOperator.GREATER_OR_EQUAL 匹配大于或等于設(shè)定值的值 

  • CompareOperator.GREATER 匹配大于設(shè)定值的值 CompareOperator.NO_OP 排除一切值

比較器種類

  • RowFilter :基于行鍵來過濾數(shù)據(jù);

  • FamilyFilterr :基于列族來過濾數(shù)據(jù);

  • QualifierFilterr :基于列限定符(列名)來過濾數(shù)據(jù);

  • ValueFilterr :基于單元格 (cell) 的值來過濾數(shù)據(jù);

  • DependentColumnFilter :指定一個參考列來過濾其他列的過濾器,過濾的原則是基于參考列的時間戳來進行篩選 。

比較器

  • BinaryComparator 使用Bytes.compareTo()比較當(dāng)前值與閾值 

  • BinaryPrefixComparator 與上面類似,但是是從左端開始前綴匹配 

  • NullComparator 不做匹配,只判斷當(dāng)前值是不是null 

  • BitComparator 通過BitwiseOp類提供的按位與(AND)、或(OR)、異或(XOR)操作執(zhí)行位級比較 ,只能用EQUAL和NOT_EQUAL

  • RegexStringComparator 根據(jù)一個正則表達式,在實例化這個比較器的時候去匹配表中的數(shù)據(jù) ,只能用* EQUAL和NOT_EQUAL

  • SubStringComparator 把閾值和表中數(shù)據(jù)當(dāng)做String實例,同時通過contains()操作匹配字符串,只能用EQUAL和NOT_EQUAL

專用過濾器

  • 單列列值過濾器 (SingleColumnValueFilter)

  • 單列列值排除器 (SingleColumnValueExcludeFilter)

  • 行鍵前綴過濾器 (PrefixFilter)

  • 列名前綴過濾器 (ColumnPrefixFilter)

  • 分頁過濾器 (PageFilter)

  • 時間戳過濾器 (TimestampsFilter)

  • 首次行鍵過濾器 (FirstKeyOnlyFilter)

包裝過濾器

  • SkipFilter過濾器,遇到需要過濾keyvalue實例時,拓張過濾整行數(shù)據(jù)

  • WhileMatchFilter過濾器 遇到一個需要過濾的 KeyValue 實例時,WhileMatchFilter 則結(jié)束本次掃描,返回已經(jīng)掃描到的結(jié)果

  • FilterList 過濾器類組合,多種類型過濾器組合。

java代碼

maven導(dǎo)包

  • 日志接口框架使用slf4j,這里去除commons-logging。

    <!-- hbase客戶端 -->
    <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-client</artifactId>
        <version>2.0.2</version>
        <!--剔除commons-logging-->
        <exclusions>
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
         </exclusions>
    </dependency>

java代碼

  • 實現(xiàn)對hbase庫數(shù)據(jù)的增刪改查,支持kerberos認證,為避免復(fù)雜參數(shù)設(shè)置,這里直接引入hadoop和hbase配置文件。

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CompareOperator;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
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.filter.Filter;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.security.UserGroupInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class HbaseUtil {
	
	private static Logger log= LoggerFactory.getLogger(HbaseUtil.class);
	
	private Connection connection;
	
	public HbaseUtil() throws IOException {
		Configuration conf = HBaseConfiguration.create();
		conf.addResource(new Path(ConfigUtil.hbaseFile));
		conf.addResource(new Path(ConfigUtil.coreFile));
		conf.addResource(new Path(ConfigUtil.hdfsFile));
		
		if(ConfigUtil.kerberos==1) {
			System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
			
			UserGroupInformation.setConfiguration(conf);
			UserGroupInformation.loginUserFromKeytab(ConfigUtil.kerberosUser,ConfigUtil.kerberosFile);
			HBaseAdmin.available(conf);
		}
		
		this.connection=ConnectionFactory.createConnection(conf);
	}
	
	
	
	/**
	 * 范圍查詢
	 * @param tableName 表名
	 * @param startRowkey 開始rowkey
	 * @param endRowkey 結(jié)束rowkey不查詢
	 * @return
	 */
	public List<String> getData(String tableName,String startRowkey,String endRowkey){
		
		log.info("Search Table {} ,Startrowkey:{} ,Endrowkey:{}",tableName,startRowkey,endRowkey);
		List<String> dataList=new ArrayList<>();
		ResultScanner resultList = null;
		String rowkey;
		
		String filterString=startRowkey.substring(4);
		try {
			Table tableModel=connection.getTable(TableName.valueOf(tableName));
			
			Scan scan = new Scan();
			
			//添加start和end
			scan.withStartRow(Bytes.toBytes(startRowkey));
			scan.withStopRow(Bytes.toBytes(endRowkey));
			scan.addColumn(Bytes.toBytes(ConfigUtil.familyName), Bytes.toBytes(ConfigUtil.cloumnName));
	        
			resultList = tableModel.getScanner(scan);
			if(resultList!=null) {
				for (Result result : resultList) {
          //TODO 添加rowkey規(guī)范驗證

					rowkey = Bytes.toString(result.getValue(Bytes.toBytes(ConfigUtil.familyName), Bytes.toBytes(ConfigUtil.cloumnName)));
					if(StringUtil.isNotEmpty(rowkey)) {
						dataList.add(rowkey);
					}
				}
			}
			
	        tableModel.close();
			
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return dataList;
	}
	
	
	/**
	 * 根據(jù)rowkey批量查詢
	 * @param tableName 表名
	 * @param rowkeyList rowkey列表
	 * @return
	 */
	public List<String> getDataList(String tableName,List<String> rowkeyList){
		
		log.info("Search Table {} ,rowkeyList:{} ",tableName,JsonUtil.toJson(rowkeyList));
		
		List<String> dataList=new ArrayList<>();
		try {
			Table tableModel=connection.getTable(TableName.valueOf(tableName));
			
			
			List<Get> getList=new ArrayList<>();
			for(String rowkey:rowkeyList) {
				getList.add(new Get(Bytes.toBytes(rowkey)));
			}
			
			//查詢
			Result[] resultList=tableModel.get(getList);
			
			//存儲數(shù)據(jù)
			if(resultList!=null&&resultList.length>0) {
				Cell[] cellList;
				for(Result result:resultList) {
					cellList=result.rawCells();
					for(Cell cell:cellList) {
						dataList.add(Bytes.toString(cell.getValueArray()));
					}
				}
			}
			
	        tableModel.close();
			
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return dataList;
	}
	
	/**
	 * 創(chuàng)建表
	 * @param tableName
	 */
	public boolean createTable(String tableName){
		try {
			//判斷數(shù)據(jù)庫是否存在
			Admin admin=this.connection.getAdmin();
			
			NamespaceDescriptor[] namespace=admin.listNamespaceDescriptors();
			int state=0;
			
			//獲取命名空間
			if(namespace.length>0) {
				for(NamespaceDescriptor name:namespace){
					if(name.getName().equals(ConfigUtil.dataName)){
						state=1;
					}
				}
			}
			
			//創(chuàng)建命名空間
			if(state==0){
				log.info("Create NameSpace {}",ConfigUtil.dataName);
				admin.createNamespace(NamespaceDescriptor.create(ConfigUtil.dataName).build());
			}
			
			TableName table= TableName.valueOf(ConfigUtil.dataName+":"+tableName);
			//創(chuàng)建表
			if(admin.tableExists(table)){
				log.info("{} tables Exists!",tableName);
				
			}else{
				log.info("Create Table {}",tableName);
	            //表描述器構(gòu)造器
	            TableDescriptorBuilder  tdb  =TableDescriptorBuilder.newBuilder(table);
	            //列族描述起構(gòu)造器
	            ColumnFamilyDescriptorBuilder cdb =  ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(ConfigUtil.familyName));
	            //存儲時間
	            cdb.setTimeToLive(ConfigUtil.saveTime*24*60*60);
	            //獲得列描述起
	            ColumnFamilyDescriptor  cfd = cdb.build();
	            //添加列族
	            tdb.setColumnFamily(cfd);
	            //獲得表描述器
	            TableDescriptor td = tdb.build();
	            //創(chuàng)建表
	            admin.createTable(td);

				log.info("{} Table Create Success!",tableName);
			}
			return true;
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return false;
	}
	
	/**
	 * 判斷表是否存在
	 * @param tableName
	 * @return
	 */
	public boolean getTableStatus(String tableName){
		try {
			Admin admin=this.connection.getAdmin();
			return admin.tableExists(TableName.valueOf(ConfigUtil.dataName+":"+tableName));
			
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return false;
	}
	
	/**
	 * 刪除表
	 */
	public boolean delTable(String tableName){
		try {
			TableName table=TableName.valueOf(ConfigUtil.dataName+":"+tableName);
			Admin admin=this.connection.getAdmin();
			if(admin.tableExists(table)){
				admin.disableTable(table);
				admin.deleteTable(table);
				log.info("Delete {} Success!",tableName);
			}else{
				log.info("No Found Table:{}",tableName);
			}
			
			return true;
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return false;
	}
	
	/**
	 * 添加數(shù)據(jù)
	 * @param tableName
	 * @param data
	 */
	public void addData(String tableName,Map<String,String> data) {
		try {
			Table tableModel=connection.getTable(TableName.valueOf(ConfigUtil.dataName+":"+tableName));
			
			List<Put> puts = new ArrayList<>();
			
			Put put;
			for(Map.Entry<String,String> entry:data.entrySet()) {
				put= new Put(Bytes.toBytes(entry.getKey()));
		        put.addColumn(Bytes.toBytes(ConfigUtil.familyName),Bytes.toBytes(ConfigUtil.cloumnName), Bytes.toBytes(entry.getValue()));
		        puts.add(put);
			}

	        tableModel.put(puts);
	        tableModel.close();
			
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
	}
	
	
	/**
	 * 關(guān)閉連接
	 */
	public void close() {
		try {
			this.connection.close();
		} catch (IOException e) {
			log.error(e.toString(),e);
		}
	}
}

到此,關(guān)于“HBase2 java Api接口舉例分析”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

網(wǎng)站名稱:HBase2javaApi接口舉例分析
網(wǎng)頁地址:http://bm7419.com/article42/igecec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、云服務(wù)器外貿(mào)建站、服務(wù)器托管網(wǎng)站收錄、域名注冊

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)