package com.day_219;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/**
* TODO
*
* @author 徐磊
* @email wc199608203213@136.com
* @data2020/02/19 上午 09:31
* @最终需求效果:
*/
public class HBaseUtils {
HBaseAdmin admin = null;
Configuration configration = null; //只要是分布式的都有 configration
private HBaseUtils(){
//连接hbase
configration = new Configuration();
// 连接Hbase要连接zk
configration.set("hbase.zookeeper.quorum", "192.168.224.132:2181"); //zookeeper保存hbase的元数据信息
// 在 hbase-site.xml 中,配置 hbase存放数据的路径
configration.set("hbase.rootdir", "hdfs://192.168.224.132:9000/hbase");
try {
admin = new HBaseAdmin(configration);
} catch (IOException e) {
e.printStackTrace();
}
}
// 一般情况下和数据库连接 都是单例的
private static HBaseUtils instance = null;
public static synchronized HBaseUtils getInstance() {
if (null == instance) { //如果只空的话,就重新 new 一个
instance = new HBaseUtils();
}
return instance;
}
/**
* 根据表名获取htable实例 进而就可以对hbase进行操作
* @param tableName
* @return
*/
public HTable getHtable(String tableName){
HTable table = null;
try {
table = new HTable(configration,tableName);
} catch (IOException e) {
e.printStackTrace();
}
return table;
}
/**
* 添加数据到hbase里面
* @param tableName 表名
* @param rowKey 对应key的值
* @param cf hbase列簇
* @param colum hbase对应的列
* @param value hbase对应的值
*/
public void put(String tableName,String rowKey,String cf,String colum,String value){
HTable table = getHtable(tableName);
Put put = new Put(Bytes.toBytes(rowKey));//hbase中的数据类型是Bytes [ ] 二进制数组类型 所以需要 Bytes.toBytes( )
put.add(Bytes.toBytes(cf),Bytes.toBytes(colum),Bytes.toBytes(value));
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
}
//测试 需要现在 Hbase 中 创建好表(规定表名,列族)
public static void main(String[] args) {
// HTable table = HBaseUtils.getInstance().getHtable("jj");
// System.out.println(table.getName().getNameAsString());
String tableName = "category_clickcount"; //需要在hbase中创建一个表 create '表名','列族名'
String rowkey="20171122_1";
String cf = "info";
String colum = "click_count";
String value = "100";
HBaseUtils.getInstance().put(tableName,rowkey,cf,colum,value);
}
//*******************进入虚拟机的hbase界面查看是否添加成功
//1.hdfs ->start-all.sh
//2.zkServer.sh start
//3.start-hbase.sh (分布式的话需要在node132和我node133(备节点)上都执行 start-hbase.sh)
//4. hbase shell
//5. list 如果里面有表名则hbase没有问题
}
HBASE 高可用搭建
链接: https://blog.csdn.net/qq_44472134/article/details/104143965