第一点:创建maven项目,在maven中引入依赖
Maven依赖
HBase 1.x版本客户端对应1.x版本的HBase集群。
HBase 2.x版本客户端对应2.x版本的HBase集群。
HBase 1.x版本
<dependency>
<groupId>com.aliyun.hbasegroupId>
<artifactId>alihbase-clientartifactId>
<version>1.1.13version>
dependency>
HBase 2.x 版本
<dependency>
<groupId>com.aliyun.hbasegroupId>
<artifactId>alihbase-clientartifactId>
<version>2.0.8version>
dependency>
然后新建类,直接上代码:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName AliyunHbaseTest
* @Description TODO
* @Author 张大仙儿
* @Date 2020/6/18 9:48
* @Version 1.0
**/
public class AliyunHbaseTest {
public static void main(String[] args) {
try {
createTable("user_table", new String[] {
"information", "contact" });
User user = new User("001", "xiaoming", "123456", "man", "20", "13355550021", "[email protected]");
insertData("user_table", user);
User user2 = new User("002", "xiaohong", "654321", "female", "18", "18757912212", "[email protected]");
insertData("user_table", user2);
List<User> list = getAllData("user_table");
System.out.println("--------------------插入两条数据后--------------------");
for (User user3 : list){
System.out.println(user3.toString());
}
System.out.println("--------------------获取原始数据-----------------------");
getNoDealData("user_table");
System.out.println("--------------------根据rowKey查询--------------------");
User user4 = getDataByRowKey("user_table", "user-001");
System.out.println(user4.toString());
// System.out.println("--------------------获取指定单条数据-------------------");
// String user_phone = getCellData("user_table", "user-001", "contact", "phone");
// System.out.println(user_phone);
// User user5 = new User("test-003", "xiaoguang", "789012", "man", "22", "12312132214", "[email protected]");
// insertData("user_table", user5);
// List list2 = getAllData("user_table");
// System.out.println("--------------------插入测试数据后--------------------");
// for (User user6 : list2){
// System.out.println(user6.toString());
// }
// deleteByRowKey("user_table", "user-test-003");
// List list3 = getAllData("user_table");
// System.out.println("--------------------删除测试数据后--------------------");
// for (User user7 : list3){
// System.out.println(user7.toString());
// }
} catch (Exception e) {
e.printStackTrace();
}
}
//创建表
public static void createTable(String tableNmae, String[] cols) throws IOException {
TableName tableName = TableName.valueOf(tableNmae);
Admin admin = initHbase().getAdmin();
if (admin.tableExists(tableName)) {
System.out.println("表已存在!");
} else {
HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
for (String col : cols) {
HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(col);
hTableDescriptor.addFamily(hColumnDescriptor);
}
admin.createTable(hTableDescriptor);
}
}
//插入数据
public static void insertData(String tableName, User user) throws IOException {
TableName tablename = TableName.valueOf(tableName);
Put put = new Put(("user-" + user.getId()).getBytes());
//参数:1.列族名 2.列名 3.值
put.addColumn("information".getBytes(), "username".getBytes(), user.getUsername().getBytes()) ;
put.addColumn("information".getBytes(), "age".getBytes(), user.getAge().getBytes()) ;
put.addColumn("information".getBytes(), "gender".getBytes(), user.getGender().getBytes()) ;
put.addColumn("contact".getBytes(), "phone".getBytes(), user.getPhone().getBytes());
put.addColumn("contact".getBytes(), "email".getBytes(), user.getEmail().getBytes());
//HTable table = new HTable(initHbase().getConfiguration(),tablename);已弃用
Table table = initHbase().getTable(tablename);
table.put(put);
}
//获取原始数据
public static void getNoDealData(String tableName){
try {
Table table= initHbase().getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
ResultScanner resutScanner = table.getScanner(scan);
for(Result result: resutScanner){
System.out.println("scan: " + result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//根据rowKey进行查询
public static User getDataByRowKey(String tableName, String rowKey) throws IOException {
Table table = initHbase().getTable(TableName.valueOf(tableName));
Get get = new Get(rowKey.getBytes());
User user = new User();
user.setId(rowKey);
//先判断是否有此条数据
if(!get.isCheckExistenceOnly()){
Result result = table.get(get);
for (Cell cell : result.rawCells()){
String colName = org.apache.hadoop.hbase.util.Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = org.apache.hadoop.hbase.util.Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
}
return user;
}
//查询指定单cell内容
public static String getCellData(String tableName, String rowKey, String family, String col){
try {
Table table = initHbase().getTable(TableName.valueOf(tableName));
String result = null;
Get get = new Get(rowKey.getBytes());
if(!get.isCheckExistenceOnly()){
get.addColumn(org.apache.hadoop.hbase.util.Bytes.toBytes(family), org.apache.hadoop.hbase.util.Bytes.toBytes(col));
Result res = table.get(get);
byte[] resByte = res.getValue(org.apache.hadoop.hbase.util.Bytes.toBytes(family), org.apache.hadoop.hbase.util.Bytes.toBytes(col));
return result = org.apache.hadoop.hbase.util.Bytes.toString(resByte);
}else{
return result = "查询结果不存在";
}
} catch (IOException e) {
e.printStackTrace();
}
return "出现异常";
}
//查询指定表名中所有的数据
public static List<User> getAllData(String tableName){
Table table = null;
List<User> list = new ArrayList<User>();
try {
table = initHbase().getTable(TableName.valueOf(tableName));
ResultScanner results = table.getScanner(new Scan());
User user = null;
for (Result result : results){
String id = new String(result.getRow());
System.out.println("用户名:" + new String(result.getRow()));
user = new User();
for(Cell cell : result.rawCells()){
String row = org.apache.hadoop.hbase.util.Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
//String family = Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength());
String colName = org.apache.hadoop.hbase.util.Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = org.apache.hadoop.hbase.util.Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
user.setId(row);
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
list.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
//删除指定cell数据
public static void deleteByRowKey(String tableName, String rowKey) throws IOException {
Table table = initHbase().getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
//删除指定列
//delete.addColumns(Bytes.toBytes("contact"), Bytes.toBytes("email"));
table.delete(delete);
}
//删除表
public static void deleteTable(String tableName){
try {
TableName tablename = TableName.valueOf(tableName);
Admin admin = initHbase().getAdmin();
admin.disableTable(tablename);
admin.deleteTable(tablename);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection initHbase() throws IOException {
// 新建一个Configuration
Configuration conf = HBaseConfiguration.create();
// 集群的连接地址,在控制台页面的数据库连接界面获得(注意公网地址和VPC内网地址)
conf.set("hbase.zookeeper.quorum", "您的阿里云hbase数据库的公网地址或者VPC内网地址");
// 设置用户名密码,默认root:root,可根据实际情况调整
conf.set("hbase.client.username", "您的AccessKey ID");
conf.set("hbase.client.password", "您的AccessKey Secret");
// 如果您直接依赖了阿里云hbase客户端,则无需配置connection.impl参数,如果您依赖了alihbase-connector,则需要配置此参数
//conf.set("hbase.client.connection.impl", AliHBaseUEClusterConnection.class.getName());
Connection connection = ConnectionFactory.createConnection(conf);
return connection;
}
}
创建测试用的user类:
public class User {
private String id;
private String username;
private String password;
private String gender;
private String age;
private String phone;
private String email;
public User(String id, String username, String password, String gender, String age, String phone, String email) {
this.id = id;
this.username = username;
this.password = password;
this.gender = gender;
this.age = age;
this.phone = phone;
this.email = email;
}
public User(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", age='" + age + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
'}';
}
}
用户名:user-001
用户名:user-002
--------------------插入两条数据后--------------------
User{
id='user-001', username='xiaoming', password='null', gender='man', age='20', phone='13355550021', email='[email protected]'}
User{
id='user-002', username='xiaohong', password='null', gender='female', age='18', phone='18757912212', email='[email protected]'}
--------------------获取原始数据-----------------------
scan: keyvalues={
user-001/contact:email/1592446661099/Put/vlen=16/seqid=0/1232821@csdn.com, user-001/contact:phone/1592446661099/Put/vlen=11/seqid=0/13355550021, user-001/information:age/1592446661099/Put/vlen=2/seqid=0/20, user-001/information:gender/1592446661099/Put/vlen=3/seqid=0/man, user-001/information:username/1592446661099/Put/vlen=8/seqid=0/xiaoming}
scan: keyvalues={
user-002/contact:email/1592446661164/Put/vlen=15/seqid=0/214214@csdn.com, user-002/contact:phone/1592446661164/Put/vlen=11/seqid=0/18757912212, user-002/information:age/1592446661164/Put/vlen=2/seqid=0/18, user-002/information:gender/1592446661164/Put/vlen=6/seqid=0/female, user-002/information:username/1592446661164/Put/vlen=8/seqid=0/xiaohong}
--------------------根据rowKey查询--------------------
User{
id='user-001', username='xiaoming', password='null', gender='man', age='20', phone='13355550021', email='[email protected]'}
Process finished with exit code 0