hbase的java集成操作代码
时间: 2023-07-02 22:13:38 浏览: 107
HBase基本操作 Java代码
以下是使用Java API连接HBase并进行操作的示例代码:
```java
import org.apache.hadoop.conf.Configuration;
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.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
public class HBaseJavaAPIExample {
private static Configuration conf = null;
private static Connection conn = null;
static {
conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "localhost"); // ZooKeeper的地址
conf.set("hbase.zookeeper.property.clientPort", "2181"); // ZooKeeper的端口号
try {
conn = ConnectionFactory.createConnection(conf);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Table table = conn.getTable(TableName.valueOf("test_table")); // 获取表对象
String rowKey = "row1";
String cf1 = "cf1";
String cf2 = "cf2";
String column1 = "column1";
String column2 = "column2";
String value1 = "value1";
String value2 = "value2";
// 添加数据
Put put = new Put(Bytes.toBytes(rowKey));
put.addColumn(Bytes.toBytes(cf1), Bytes.toBytes(column1), Bytes.toBytes(value1));
put.addColumn(Bytes.toBytes(cf2), Bytes.toBytes(column2), Bytes.toBytes(value2));
table.put(put);
// 查询数据
Get get = new Get(Bytes.toBytes(rowKey));
Result result = table.get(get);
byte[] value1Bytes = result.getValue(Bytes.toBytes(cf1), Bytes.toBytes(column1));
byte[] value2Bytes = result.getValue(Bytes.toBytes(cf2), Bytes.toBytes(column2));
String value1Query = Bytes.toString(value1Bytes);
String value2Query = Bytes.toString(value2Bytes);
System.out.println("查询结果:" + value1Query + "," + value2Query);
// 删除数据
Delete delete = new Delete(Bytes.toBytes(rowKey));
delete.addColumn(Bytes.toBytes(cf1), Bytes.toBytes(column1));
table.delete(delete);
table.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们创建了一个HBaseConfiguration对象,并通过它设置了ZooKeeper的地址和端口号。然后我们通过ConnectionFactory来创建一个Connection对象。接着我们使用该Connection对象来获取Table对象,然后执行添加、查询和删除数据的操作。最后我们关闭了Table和Connection对象。
阅读全文