使用Java對(duì)Hbase操作總結(jié)及示例代碼
前面已經(jīng)給大家講解過(guò)如何使用Hbase建表,以及基本的操作和一些常用shell命令,今天就給大家介紹下如何使用java對(duì)Hbase進(jìn)行各種操作。
沒(méi)印象的話可以再去瀏覽下:
Hbase入門(mén)教程,shell命令大全講解
Java操作Hbase主要方法:
1.Configuration
在使用Java API時(shí),Client端需要知道HBase的配置環(huán)境,如存儲(chǔ)地址,zookeeper等信息。
這些信息通過(guò)Configuration對(duì)象來(lái)封裝,可通過(guò)如下代碼構(gòu)建該對(duì)象:
Configuration config = HBaseConfiguration.create();
在調(diào)用HBaseConfiguration.create()方法時(shí),HBase首先會(huì)在classpath下查找hbase-site.xml文件,將里面的信息解析出來(lái)封裝到Configuration對(duì)象中,如果hbase-site.xml文件不存在,則使用默認(rèn)的hbase-core.xml文件。
2.HBaseAdmin
HBaseAdmin用于創(chuàng)建數(shù)據(jù)庫(kù)表格,并管理表格的元數(shù)據(jù)信息,通過(guò)如下方法構(gòu)建:
HBaseAdmin admin=new HBaseAdmin(config);
3.HTableDescriptor
在HTableDescriptor中,建立了一個(gè)表結(jié)構(gòu),HTableDescriptor封裝表格對(duì)象,對(duì)表格的增刪改查操作主要通過(guò)它來(lái)完成,構(gòu)造方法如下:
HTableDescriptor table = new HTableDescriptor(TableName.valueOf(“表名”));
4.addFamily
addFamily用于建立表下的列簇,并存放到表結(jié)構(gòu),方法如下:
HColumnDescriptor base = new HColumnDescriptor(“列簇名”);
table.addFamily(base);
代碼如下:
首先建一個(gè)maven工程,導(dǎo)入依賴包導(dǎo)pom.xml
<dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-common</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-server</artifactId> <version>1.2.0</version> </dependency
1、創(chuàng)建表操作
public class HBaseClient { public void createTable() throws IOException { // 1. 創(chuàng)建配置 Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","ip1"); //hbase主默認(rèn)端口是60000 conf.set("hbase.master","ip1:60000"); //zookeeper客戶端的端口號(hào)2181 conf.set("hbase.zookeeper.property.clientPort","2181"); // 2. 創(chuàng)建連接 Connection conn = ConnectionFactory.createConnection(conf); //3.獲得一個(gè)建表、刪表的對(duì)象hbaseAdmin()是繼承admin() Admin admin = conn.getAdmin(); // 4. 創(chuàng)建表的描述信息 HTableDescriptor student = new HTableDescriptor(TableName.valueOf("表名")); // 5. 添加列簇 student.addFamily(new HColumnDescriptor("列簇名1")); student.addFamily(new HColumnDescriptor("列簇名2")); // 6. 調(diào)用API進(jìn)行建表操作 admin.createTable(student); } }
2、判斷表是否存在
public void isTableExists() throws IOException { // 1. 創(chuàng)建配置 Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","ip1"); conf.set("hbase.zookeeper.property.clientPort","2181"); // 2. 創(chuàng)建連接 Connection conn = ConnectionFactory.createConnection(conf); // 3. 創(chuàng)建admin Admin admin = conn.getAdmin(); // 4. 調(diào)用API進(jìn)行判斷表是否存在 System.out.println(admin.tableExists(TableName.valueOf("表名"))); }
3、向表中插入數(shù)據(jù)
public void putData2Table() throws IOException { // 1. 創(chuàng)建配置 Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","ip1"); conf.set("hbase.zookeeper.property.clientPort","2181"); // 2. 創(chuàng)建連接 Connection conn = ConnectionFactory.createConnection(conf); // 3. 創(chuàng)建Table類(lèi) Table student = conn.getTable(TableName.valueOf("表名")); // 4. 創(chuàng)建Put類(lèi) Put put = new Put(Bytes.toBytes("1001")); // 5. 向Put中添加 列簇,列名,值 注意:需要轉(zhuǎn)化成字節(jié)數(shù)組 put.addColumn(Bytes.toBytes("列簇1"),Bytes.toBytes("列1"),Bytes.toBytes("zhangsan")); put.addColumn(Bytes.toBytes("列簇1"),Bytes.toBytes("列2"),Bytes.toBytes("female")); put.addColumn(Bytes.toBytes("列簇2"),Bytes.toBytes("列3"),Bytes.toBytes("math")); put.addColumn(Bytes.toBytes("列簇2"),Bytes.toBytes("列4"),Bytes.toBytes("89")); // 6.調(diào)用API進(jìn)行插入數(shù)據(jù) student.put(put); }
4、查看一條數(shù)據(jù)
public void getDataFromTable() throws IOException { // 1. 創(chuàng)建配置 Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","ip1"); conf.set("hbase.zookeeper.property.clientPort","2181"); // 2. 創(chuàng)建連接 Connection conn = ConnectionFactory.createConnection(conf); // 3. 創(chuàng)建Table類(lèi) Table student = conn.getTable(TableName.valueOf("表名")); // 4. 創(chuàng)建 Get 類(lèi) Get get = new Get(Bytes.toBytes("1001")); // 5.調(diào)用API進(jìn)行獲取數(shù)據(jù) Result result = student.get(get); // 6. 將返回的結(jié)果進(jìn)行遍歷輸出 Cell[] cells = result.rawCells(); for (Cell cell : cells) { System.out.println("rowkey :"+Bytes.toString(CellUtil.cloneRow(cell))); System.out.println("列簇 :"+Bytes.toString(CellUtil.cloneFamily(cell))); System.out.println("列名 :"+Bytes.toString(CellUtil.cloneQualifier(cell))); System.out.println("值 :"+Bytes.toString(CellUtil.cloneValue(cell))); System.out.println("----------------"); } }
5、刪除表操作
public void dropTable() throws IOException { // 1. 創(chuàng)建配置 Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","ip1"); conf.set("hbase.zookeeper.property.clientPort","2181"); // 2. 創(chuàng)建連接 Connection conn = ConnectionFactory.createConnection(conf); // 3. 創(chuàng)建admin Admin admin = conn.getAdmin(); // 4. 調(diào)用API禁用表 admin.disableTable(TableName.valueOf("表名")); // 5. 調(diào)用API刪除表 admin.deleteTable(TableName.valueOf("表名")); } }
6、刪除hbase中的table里面的rowkey
public static void deleteRow(String tableName,String rowKey) throws Exception{ HTable hTable = new HTable(configuration,tableName); Delete delete = new Delete(rowKey.getBytes()); List<Delete> list = new ArrayList<Delete>(); list.add(delete); hTable.delete(list); }
7、查詢r(jià)ow = rowKey的數(shù)據(jù)
public static void getRow(String tableName,String rowKey) throws Exception{ HTable hTable = new HTable(configuration, tableName); Get get = new Get(rowKey.getBytes()); Result result = hTable.get(get); for(KeyValue value:result.raw()){ System.out.println("cf:"+new String(value.getFamily())+new String(value.getQualifier())+"="+new String(value.getValue())); } }
8、查詢r(jià)owkey在startRow和endRow之間的數(shù)據(jù),及rowkey的范圍查詢
Put、Delete與Get對(duì)象都是Row的子類(lèi),從該繼承關(guān)系中我們就可以了解到Get、Delete與Pu對(duì)象本身就只能進(jìn)行單行的操作,
HBase客戶端還提供了一套能夠進(jìn)行全表掃描的API,方便用戶能夠快速對(duì)整張表進(jìn)行掃描,以獲取想要的結(jié)果—scan:
public static void getBetweenRow(String tableName,String startRow,String stopRow) throws Exception{ HTable table = new HTable(configuration, tableName); Scan scan = new Scan(); scan.addColumn("cf1".getBytes(), "colum1".getBytes()); scan.addColumn("cf1".getBytes(), "colum2".getBytes()); scan.addColumn("cf1".getBytes(), "colum3".getBytes()); scan.setStartRow(startRow.getBytes()); scan.setStopRow(stopRow.getBytes()); ResultScanner scanner = table.getScanner(scan); for(Result result:scanner){ for(KeyValue value:result.raw()){ System.out.println("cf:"+new String(value.getFamily())+new String(value.getQualifier())+"="+new String(value.getValue())); } } }
9、批量寫(xiě)入
public <T> void puts(String tableName, Map<String, Object> items) { if (items == null || items.isEmpty()) { LOG.error("[HBase] Adding null/empty item map!"); return; } int maxSize = 10000; Table table = null; try { table = con.getTable(TableName.valueOf(tableName)); int eachSize = Math.min(maxSize, items.size()); List<Put> puts = new ArrayList<Put>(eachSize); int handled = 0; for (Entry<String, Object> entry : items.entrySet()) { String ultimateRowKey = getHashedID(entry.getKey()); Object value = entry.getValue(); if (ultimateRowKey == null || ultimateRowKey.isEmpty()) { LOG.error("[HBase] Adding null/empty hashed key! Original key is " + entry.getKey()); handled++; continue; } Put put = new Put(Bytes.toBytes(ultimateRowKey)); put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("ab"), Bytes.toBytes(value .getAb())); put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("dt"), Bytes.toBytes(value .getDt())); put.addColumn(Bytes.toBytes(familyName1), Bytes.toBytes("hb"), Bytes.toBytes(value .getHb())); Gson gson = new Gson(); String valuestr = gson.toJson(value); put.addColumn(Bytes.toBytes(familyName2), Bytes.toBytes("js"), Bytes.toBytes(valuestr)); puts.add(put); handled++; // 每隔10000,寫(xiě)一次 if (handled == eachSize) { LOG.info("[HBase] Adding " + eachSize + "rows!"); table.put(puts); puts = new ArrayList<Put>(eachSize); } } if (puts.size() > 0) table.put(puts); } catch (IOException e) { LOG.error("[HBase] Error while putting data " + e.getMessage()); } finally { try { if (table != null) table.close(); } catch (IOException e) { LOG.error("[HBase] Error while closing table " + e.getMessage()); } } }
到此這篇關(guān)于使用Java對(duì)Hbase操作總結(jié)及示例代碼的文章就介紹到這了,更多相關(guān)Java操作hbase總結(jié)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot詳細(xì)講解如何創(chuàng)建及刷新Spring容器bean
前面看spring源碼時(shí)可以發(fā)現(xiàn)refresh()方法十分重要。在這個(gè)方法中會(huì)加載beanDefinition,同時(shí)創(chuàng)建bean對(duì)象。那么在springboot中有沒(méi)有使用這個(gè)refresh()方法呢2022-06-06MyBatis-Plus 自定義sql語(yǔ)句的實(shí)現(xiàn)
這篇文章主要介紹了MyBatis-Plus 自定義sql語(yǔ)句的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12超詳細(xì)講解Java秒殺項(xiàng)目登陸模塊的實(shí)現(xiàn)
這是一個(gè)主要使用java開(kāi)發(fā)的秒殺系統(tǒng),項(xiàng)目比較大,所以本篇只實(shí)現(xiàn)了登陸模塊,代碼非常詳盡,感興趣的朋友快來(lái)看看2022-03-03Spring Boot教程之利用ActiveMQ實(shí)現(xiàn)延遲消息
這篇文章主要給大家介紹了關(guān)于Spring Boot教程之利用ActiveMQ實(shí)現(xiàn)延遲消息的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11在IDEA中創(chuàng)建Web項(xiàng)目的詳細(xì)過(guò)程
這篇文章主要給大家介紹了關(guān)于在IDEA中創(chuàng)建Web項(xiàng)目的詳細(xì)過(guò)程,很多朋友可能在學(xué)習(xí)java基礎(chǔ)的時(shí)候已經(jīng)熟練掌握了IDEA創(chuàng)建java項(xiàng)目的基本步驟,但隨著學(xué)習(xí)技術(shù)的不斷深入,不同的IDEA版本可能在項(xiàng)目的創(chuàng)建頁(yè)面上出現(xiàn)些許的出入,需要的朋友可以參考下2023-10-10java內(nèi)部類(lèi)的那些事兒_讓你一看就弄明白
本篇文章介紹了,java內(nèi)部類(lèi)的那些事兒。需要的朋友參考下2013-05-05Java MongoDB數(shù)據(jù)庫(kù)連接方法梳理
MongoDB作為一種介于關(guān)系型數(shù)據(jù)庫(kù)和非關(guān)系型數(shù)據(jù)庫(kù)之間的產(chǎn)品,它可以提供可擴(kuò)展的高性能的數(shù)據(jù)存儲(chǔ)解決方案,近些年來(lái)受到了開(kāi)發(fā)者的喜愛(ài)2022-08-08