访问Hbase,待更新方法一

本文介绍了三种访问HBase的方法:使用HbaseTemplate工具类、通过HBase线程池以及配置XML文件并通过Java读取配置的方式。文章详细展示了每种方法的具体实现步骤及代码示例。

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

访问Hbase的三种方法:
方法一:HbaseTemlate工具类
(1)配置文件:src\main\resources\spring-hbase.xml
<?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xmlns:hdp="http://www.springframework.org/schema/hadoop"  
   xmlns:beans="http://www.springframework.org/schema/beans"  
   xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/hadoop http://www.springframework.org/schema/hadoop/spring-hadoop.xsd">  
      <!-- 配置zookeeper的信息,远程连接hbase时使用 -->  
    <hdp:configuration resources="classpath:/hbase-site.xml" />  
    <hdp:hbase-configuration configuration-ref="hadoopConfiguration" />  
    <!-- 配置HbaseTemplate -->  
    <bean id="htemplate" class="org.springframework.data.hadoop.hbase.HbaseTemplate">  
        <property name="configuration" ref="hbaseConfiguration">  
        </property>  
        <property name="encoding" value="UTF-8"></property>  
    </bean>  
 </beans>  
(2)配置文件:src\main\resources\hbase-site.xml
<?xml version="1.0"?>  
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>  
<configuration> 
    <!-- zookeeper集群的URL配置 --> 
    <property>  
        <name>hbase.zookeeper.quorum</name>  
        <value>namenode1-sit.cnsuning.com,namenode2-sit.cnsuning.com,slave01-sit.cnsuning.com</value>  
    </property> 
    <!-- 客户端连接端口 --> 
    <property>  
        <name>hbase.zookeeper.property.clientPort</name>  
        <value>2015</value>  
    </property>
    <!-- 重试等待时间 -->
    <property>  
        <name>hbase.client.pause</name>  
        <value>50</value>  
    </property>
    <!-- 失败时重试次数 -->
    <property>  
        <name>hbase.client.retries.number</name>  
        <value>3</value>  
    </property>
    <!-- RPC请求的超时时间。如果某次RPC时间超过该值,客户端就会主动关闭socket -->
    <property>  
        <name>hbase.rpc.timeout</name>  
        <value>2000</value>  
    </property>
    <!-- HBase客户端发起一次数据操作直至得到响应之间总的超时时间 -->
    <property>  
        <name>hbase.client.operation.timeout</name>  
        <value>3000</value>  
    </property>
    <!-- 该参数是表示HBase客户端发起一次scan操作的rpc调用至得到响应之间总的超时时间 -->
    <property>  
        <name>hbase.client.scanner.timeout.period</name>  
        <value>10000</value>  
    </property>
</configuration>  
(2)java程序:
static private ApplicationContext hbaseContext = new ClassPathXmlApplicationContext("classpath:spring-hbase.xml");
static private BeanFactory factory = (BeanFactory) hbaseContext;   
static private HbaseTemplate htemplate = (HbaseTemplate) factory.getBean("htemplate");
static private GetRow getRow = new GetRow();//回调函数
 String tableName = "ns_sousuo:tdm_empower_gds_init_d";
 String rowKey = "20160919_000000_ka_000000300_000000000";
 System.setProperty("HADOOP_USER_NAME", "sousuo");
 String hbaseRes = "";
 try{
      hbaseRes = htemplate.get(tableName, rowKey, getRow);
 }catch(Exception e){
      logger.error(e.getMessage(), e);
 }
其中回调函数GetRow如下
public String mapRow(Result result, int rowNum) throws Exception {   
    String hbaseRes = "";
        List<Cell> ceList =   result.listCells();  
             if(ceList!=null&&ceList.size()>0){  
                 for(Cell cell:ceList){  
                hbaseRes += Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength())+  
                             "_"+Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength())
                              +"="+Bytes.toString( cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())+" ";
            }  
        }  
        return hbaseRes;  
    } 






方法二:Hbase线程池访问:
Map<String,String> numAndPort = getNumAndPort();
        Configuration configuration = HBaseConfiguration.create(); 
        configuration.set("hbase.zookeeper.quorum", numAndPort.get("hbase.zookeeper.quorum")); 
        configuration.set("hbase.zookeeper.property.clientPort", numAndPort.get("hbase.zookeeper.property.clientPort")); 
        HConnection connection = null;
        HTableInterface table = null;
        try {
        configuration.set("hbase.client.pause", "50"); //重试等待时间
        configuration.set("hbase.client.retries.number", "3"); //失败时重试次数
        configuration.set("hbase.rpc.timeout", "2000"); //RPC请求的超时时间。如果某次RPC时间超过该值,客户端就会主动关闭socket
        configuration.set("hbase.client.operation.timeout", "3000"); //HBase客户端发起一次数据操作直至得到响应之间总的超时时间
        configuration.set("hbase.client.scanner.timeout.period", "10000");//该参数是表示HBase客户端发起一次scan操作的rpc调用至得到响应之间总的超时时间
        connection = HConnectionManager.createConnection(configuration);
        table = connection.getTable(tableName);
hbaseRes = getHbaseRow(table, tableName, rowKey);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}finally {
table.close();
            connection.close();
}




getHbaseRow方法:
public static String getHbaseRow(HTableInterface table, String tableName, String row) throws Exception {
        Get get = new Get(Bytes.toBytes(row));
        Result result = table.get(get);
        String returnResult = "";
        // 输出结果,raw方法返回所有keyvalue数组
        for (KeyValue rowKV : result.raw()) {
            System.out.print("行名:" + new String(rowKV.getRow()) + " ");
            System.out.print("时间戳:" + rowKV.getTimestamp() + " ");
            System.out.print("列族名:" + new String(rowKV.getFamily()) + " ");
            System.out.print("列名:" + new String(rowKV.getQualifier()) + " ");
            System.out.println("值:" + new String(rowKV.getValue()));
            returnResult = new String(rowKV.getValue());
        }
        return returnResult;
    }








方法三:将Hbase的配置写到一般的xml,然后用java获取配置文件中的内容:
(1)配置文件:
<?xml version="1.0"?>  
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>  
<configuration>  
    <property name="hbase.zookeeper.quorum" value= "namenode1-sit.cnsuning.com,namenode2-sit.cnsuning.com,slave01-sit.cnsuning.com">  
    </property>  
    <property name="hbase.zookeeper.property.clientPort" value="2015">   
    </property>  
</configuration>  
(2)java程序:
Map<String,String> numAndPort = getNumAndPort();
        Configuration configuration = HBaseConfiguration.create(); 
        configuration.set("hbase.zookeeper.quorum", numAndPort.get("hbase.zookeeper.quorum")); 
        configuration.set("hbase.zookeeper.property.clientPort", numAndPort.get("hbase.zookeeper.property.clientPort")); 
        HBaseAdmin hAdmin = new HBaseAdmin(configuration);
        boolean aa = hAdmin.tableExists("ns_sousuo:tdm_empower_gds_init_d");
        if(aa)
        {
        System.out.println("表存在!!!");
        HTable table = new HTable(configuration, "ns_sousuo:tdm_empower_gds_init_d");
            Scan scan = new Scan();
            ResultScanner results = table.getScanner(scan);
            // 输出结果
            for (Result result1 : results) {
                for (KeyValue rowKV : result1.raw()) {
                    System.out.print("行名:" + new String(rowKV.getRow()) + " ");
                    System.out.print("时间戳:" + rowKV.getTimestamp() + " ");
                    System.out.print("列族名:" + new String(rowKV.getFamily()) + " ");
                    System.out
                            .print("列名:" + new String(rowKV.getQualifier()) + " ");
                    System.out.println("值:" + new String(rowKV.getValue()));
                }
            }
        }
        else
        {
        System.out.println("表不存在!!!");
        }
### HBase 实时数据更新方法 HBase种分布式 NoSQL 数据库,支持高效的实时读写操作。为了实现实时数据更新HBase 提供了几种机制来满足不同的需求。 #### 1. **基于 Put 和 Delete 的更新** HBase 中的数据更新主要依赖 `Put` 和 `Delete` 操作。当执行 `Put` 操作时,新版本的数据会被追加到存储中,并带有时间戳标记[^3]。如果需要删除某些数据,则可以通过 `Delete` 命令移除指定的单元格或整行数据。由于 HBase 支持多版本控制 (MVCC),旧版本的数据仍然保留直到被垃圾回收机制清理掉。 #### 2. **利用 Phoenix 进行 SQL 风格的更新** Apache Phoenix 是构建在 HBase 上的个开源项目,它允许开发者通过标准 SQL 接口访问 HBase 表中的数据[^5]。借助 Phoenix,用户可以直接使用 `UPDATE` 或 `UPSERT` 语句完成复杂的批量修改任务。这种方式不仅简化了开发流程,还提供了更强大的索引管理能力,从而加速查询性能并保障致性。 #### 3. **增量加载与同步策略** 对于大规模生产环境下的应用来说,仅仅依靠单条记录级别的变更可能不够高效。此时可以考虑采用增量导入的方式定期捕获源系统的最新变动部分再将其同步至目标端——即此处提到的 HBase 。具体做法包括但不限于依据预设的时间范围筛选符合条件的新增/修改项作为待迁移对象列表;随后针对该集合发起针对性检索请求获取实际内容最后实施持久化入库动作[^2]。 #### 4. **事务处理的支持** 尽管传统意义上的 ACID 特性并非原生存在于 HBase 当中 ,但是随着技术发展目前已经存在多种途径达成近似效果比如 Coprocessor 执行框架配合自定义逻辑或者引入第三方工具包如 Apache Kudu 来弥补这短板以便更好地服务于那些对可靠度要求极高的场景下运行的应用程序实例们. 综上所述,Hbase 可以通过以上几种方式实现其内部结构里所保存着的信息元素们的即时刷新调整过程. ```python from happybase import Connection def update_hbase_data(table_name, row_key, data_dict): connection = Connection('localhost') table = connection.table(table_name) with table.batch() as b: for column_family, columns in data_dict.items(): for col, value in columns.items(): full_col = f"{column_family}:{col}" b.put(row_key, {full_col: str(value)}) connection.close() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值