博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
封装一个简单的HBaseUtil
阅读量:778 次
发布时间:2019-03-23

本文共 2576 字,大约阅读时间需要 8 分钟。

文章目录

前言

HBase作为一个面向列族的数据库,和一般的数据库不同,没法用JDBC封装的那套util,便重新封装了个HBase自己的util供项目使用。

Maven依赖

注意修改成自己的版本,可以去https://mvnrepository.com/artifact/org.apache.hbase/hbase-client和https://mvnrepository.com/artifact/org.apache.hbase/hbase-server选择版本。

org.apache.hbase
hbase-server
1.4.5
org.apache.hbase
hbase-client
1.4.5

私有属性

声明一些私有属性

private Configuration hbaseConf;	private Connection hbaseConn;	private HBaseAdmin admin;

构造方法

需要将这些文件放到resources,直接用集群文件中的就行;当然也可以手写但是太过麻烦,毕竟有hadoop、zookpeer、hbase三者的信息。

在这里插入图片描述

代码

public HBaseUtil() {		hbaseConf =  HBaseConfiguration.create();		try {			hbaseConn = ConnectionFactory.createConnection();			admin = (HBaseAdmin) hbaseConn.getAdmin();			System.out.println("连接上了吗?"+!hbaseConn.isClosed());		} catch (IOException e) {			e.printStackTrace();		}			}

演示

在这里插入图片描述

表格操作

判断是否存在

public boolean isExist(String tableNameStr){		TableName tableName = TableName.valueOf(tableNameStr);		boolean flag = false;		try {			flag = admin.tableExists(tableName);		} catch (IOException e) {			e.printStackTrace();		}		return flag;	}

新建表格

public void createTable(String tableNameStr,String[] familys){		if(this.isExist(tableNameStr)){			System.out.println("表格已经存在了");			return;		}		TableName tableName = TableName.valueOf(tableNameStr);		//表描述		HTableDescriptor table = new HTableDescriptor(tableName);		//列族描述		for(String familyStr:familys){			HColumnDescriptor family = new HColumnDescriptor(familyStr);			table.addFamily(family);		}		try {			admin.createTable(table);		} catch (IOException e) {			e.printStackTrace();		}	}

删除表格

public void dropTable(String tableName) { 	        try { 	            admin.disableTable(tableName); 	            admin.deleteTable(tableName); 	        } catch (MasterNotRunningException e) { 	            e.printStackTrace(); 	        } catch (ZooKeeperConnectionException e) { 	            e.printStackTrace(); 	        } catch (IOException e) { 	            e.printStackTrace(); 	        } 	   	    }

数据操作

添加或者修改

一条数据

public void putData(String tableNameStr,Put put){		TableName tableName = TableName.valueOf(tableNameStr);		Table table;		try {			table = hbaseConn.getTable(tableName);			table.put(put);		} catch (IOException e) {			e.printStackTrace();		}			}

多条数据

public void putData(String tableNameStr,List
putList){ TableName tableName = TableName.valueOf(tableNameStr); Table table; try { table = hbaseConn.getTable(tableName); table.put(putList); } catch (IOException e) { e.printStackTrace(); } }

转载地址:http://rejzk.baihongyu.com/

你可能感兴趣的文章