溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

HBase2 java Api接口舉例分析

發(fā)布時(shí)間:2021-11-24 14:24:29 來源:億速云 閱讀:138 作者:iii 欄目:大數(shù)據(jù)

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

接口介紹

攔截器

  • 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 :指定一個(gè)參考列來過濾其他列的過濾器,過濾的原則是基于參考列的時(shí)間戳來進(jìn)行篩選 。

比較器

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

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

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

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

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

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

專用過濾器

  • 單列列值過濾器 (SingleColumnValueFilter)

  • 單列列值排除器 (SingleColumnValueExcludeFilter)

  • 行鍵前綴過濾器 (PrefixFilter)

  • 列名前綴過濾器 (ColumnPrefixFilter)

  • 分頁過濾器 (PageFilter)

  • 時(shí)間戳過濾器 (TimestampsFilter)

  • 首次行鍵過濾器 (FirstKeyOnlyFilter)

包裝過濾器

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

  • WhileMatchFilter過濾器 遇到一個(gè)需要過濾的 KeyValue 實(shí)例時(shí),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代碼

  • 實(shí)現(xiàn)對hbase庫數(shù)據(jù)的增刪改查,支持kerberos認(rèn)證,為避免復(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ī)范驗(yàn)證

					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));
	            //存儲時(shí)間
	            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é)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI