Hbase 的javaAPI基本操作用 在idea上的实现

本文详细介绍了如何在HBase集群上搭建环境,并通过Java进行表的创建、数据插入及删除操作。从pom文件配置到hbase-site.xml设置,再到具体Java代码实现,全面覆盖HBase操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.保证集群开启:

jps有如下进程

2.pom文件中的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zhiyou100</groupId>
    <artifactId>hbasedemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <hbase.version>1.4.8</hbase.version>
    </properties>

    <dependencies>
        <!--hbase-->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>${hbase.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-common</artifactId>
            <version>${hbase.version}</version>
        </dependency>
        <!--要使用HBase的MapReduce API-->
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>${hbase.version}</version>
        </dependency>
    </dependencies>
    
</project>

3.编写配置文件:hbase-site.xml

将集群上$HBASE_HOME/conf/hbase-site.xml拷贝过来就可以,也可以直接复制下面内容

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
-->
<configuration>
    <property>
        <name>hbase.rootdir</name>
        <value>hdfs://master2:9000/hbase</value>
    </property>
    <property>
        <name>hbase.cluster.distributed</name>
        <value>true</value>
    </property>
<!--conf.set("hbase.zookeeper.quorum", "master2");-->
    <!--// 设置Zookeeper,直接设置IP地址-->
    <property>
        <name>hbase.zookeeper.quorum</name>
        <value>master2</value>
    </property>

</configuration>

---注意:如果没有再本地的C:\Windows\System32\drivers\etc路径下的hosts文件中配置IP 与之对应的主机名

请将上面的主机名(master2)填写成自己的IP

4.编写java代码--创建类:HBaseDDL

package com.hbase.DDL;

import com.google.common.io.Resources;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseDDL {
    private static Configuration configuration;
    private static Connection connection;
    private static Admin admin;
    static {
        //1.获得Configuration实例并进行相关设置
        configuration = HBaseConfiguration.create();
        configuration.addResource(Resources.getResource("hbase-site.xml"));
        //2.获得Connection实例
        try {
            connection = ConnectionFactory.createConnection(configuration);
            //3.1获得Admin接口
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        //创建表
        String  familyNames[]={"nature","social"};
        createTable("test_hbase",familyNames);
        //向表中插入数据
        insert("test_hbase","libai","nature","height","25");
        //删除表
        dropTable("test_hbase");
    }
    /**
     * 创建表
     * @param tableName 表名
     * @param familyNames 列族名
     * */
    public static void createTable(String tableName, String familyNames[]) throws IOException {
        //如果表存在退出
        if (admin.tableExists(TableName.valueOf(tableName))) {
            System.out.println("Table exists!");
            return;
        }
        //通过HTableDescriptor类来描述一个表,HColumnDescriptor描述一个列族
        HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
        for (String familyName : familyNames) {
            tableDescriptor.addFamily(new HColumnDescriptor(familyName));
        }
        //tableDescriptor.addFamily(new HColumnDescriptor(familyName));
        admin.createTable(tableDescriptor);
        System.out.println("createtable success!");
    }

    /**
     * 删除表
     * @param tableName 表名
     * */
    public static void dropTable(String tableName) throws IOException {
        //如果表不存在报异常
        if (!admin.tableExists(TableName.valueOf(tableName))) {
            System.out.println(tableName+"不存在");
            return;
        }

        //删除之前要将表disable
        if (!admin.isTableDisabled(TableName.valueOf(tableName))) {
            admin.disableTable(TableName.valueOf(tableName));
        }
        admin.deleteTable(TableName.valueOf(tableName));
        System.out.println("deletetable " + tableName + "ok.");
    }

    /**
     * 指定行/列中插入数据
     * @param tableName 表名
     * @param rowKey 主键rowkey
     * @param family 列族
     * @param column 列
     * @param value 值
     * TODO: 批量PUT
     */
    public static void insert(String tableName, String rowKey, String family, String column, String value) throws IOException {
        //3.2获得Table接口,需要传入表名
        Table table =connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(Bytes.toBytes(rowKey));
        put.addColumn(Bytes.toBytes(family), Bytes.toBytes(column), Bytes.toBytes(value));
        table.put(put);
        System.out.println("insertrecored " + rowKey + " totable " + tableName + "ok.");
    }

    /**
     * 删除表中的指定行
     * @param tableName 表名
     * @param rowKey rowkey
     * TODO: 批量删除
     */
    public static void delete(String tableName, String rowKey) throws IOException {
        //3.2获得Table接口,需要传入表名
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(Bytes.toBytes(rowKey));
        table.delete(delete);
    }
}

 

测试:1.创建表-----createTable("test_hbase",familyNames);

在hbase shell中list查看表


2.向创建的表中插入数据-----insert("test_hbase","luban","nature","height","250");

在hbase shell中scan 'test_hbase'查看表内容


3.删除表------dropTable("test_hbase");

在hbase shell中list查看表,已经没有了test_hbase

 

转载于:https://www.cnblogs.com/pigdata/p/10305588.html

### 如何在 IntelliJ IDEA 中使用 HBase Java API #### 配置 Maven 工程 为了在 IntelliJ IDEA 中使用 HBase Java API,首先需要创建一个 Maven 项目并添加必要的依赖项。以下是具体的配置过程: Maven 是一种常用的构建工具,可以通过 `pom.xml` 文件管理项目的依赖关系。对于 HBase 的开发环境,需要在 `pom.xml` 文件中引入 HBase 客户端库以及其相关依赖项[^3]。 ```xml <dependencies> <!-- HBase Client Dependency --> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>2.4.9</version> <!-- 替换为你使用的具体版本号 --> </dependency> <!-- Zookeeper Dependency (如果未被自动包含) --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.7.0</version> <!-- 替换为你使用的具体版本号 --> </dependency> </dependencies> ``` 完成上述配置后,右键单击 `pom.xml` 文件,选择 **Maven -> Reimport** 来刷新依赖项。 --- #### 设置 HBase 配置文件 HBase 使用 XML 格式的配置文件来定义运行参数。通常情况下,这些配置会被放置在一个名为 `hbase-site.xml` 的文件中。该文件应该位于项目的类路径下(通常是 `src/main/resources/`),以便应用程序能够加载它[^1]。 以下是一个典型的 `hbase-site.xml` 文件的内容示例: ```xml <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <configuration> <property> <name>hbase.zookeeper.quorum</name> <value>localhost</value> <!-- 替换为实际的 ZooKeeper 地址 --> </property> <property> <name>hbase.zookeeper.property.clientPort</name> <value>2181</value> <!-- 替换为实际的 ZooKeeper 端口 --> </property> </configuration> ``` 此文件的作用是指定 HBase 和 ZooKeeper 的连接信息,从而允许客户端程序定位集群中的 Master 节点和 RegionServer 实例。 --- #### 编写 HBase 连接代码 一旦完成了 Maven 依赖导入和配置文件设置,就可以编写用于访问 HBase 数据表的应用逻辑了。下面展示了一个简单的例子,演示如何通过 HBase Java API 创建连接、执行基本操作,并最终释放资源[^2]。 ```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.*; import java.io.IOException; public class HBaseExample { public static void main(String[] args) throws IOException { // 初始化 Configuration 对象 Configuration config = HBaseConfiguration.create(); try (Connection connection = ConnectionFactory.createConnection(config)) { // 自动关闭连接 TableName tableName = TableName.valueOf("my_table"); Table table = connection.getTable(tableName); System.out.println("成功获取表格:" + tableName); // 添加更多业务逻辑... } catch (IOException e) { System.err.println("发生错误:" + e.getMessage()); } } } ``` 注意:每次调用完 `ConnectionFactory.createConnection()` 方法返回的对象时,都应当显式地将其关闭以避免内存泄漏问题。 --- #### 测试与调试 当一切准备就绪后,可以尝试启动应用测试是否能正常工作。如果遇到任何异常情况,则可能需要重新核查以下几个方面: - 是否正确指定了目标机器上的 HBase/ZooKeeper IP 或主机名; - 当前用户的权限是否满足需求; - 版本兼容性是否存在冲突等问题。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值