2025/2/11

Scala可以通过HBase的Java API与HBase进行交互,实现数据的读写操作。本篇博客将展示如何使用Scala操作HBase。
HBase Java API:使用Configuration、Table和Put类。
数据操作:插入、查询和删除数据。
示例代码:

 

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hbase.HBaseConfiguration
import org.apache.hadoop.hbase.client.{ConnectionFactory, Put, Table}
import org.apache.hadoop.hbase.util.Bytes

object HBaseExample {
def main(args: Array[String]): Unit = {
val conf: Configuration = HBaseConfiguration.create()
conf.set("hbase.zookeeper.quorum", "localhost")
conf.set("hbase.zookeeper.property.clientPort", "2181")

val connection = ConnectionFactory.createConnection(conf)
val table: Table = connection.getTable(Bytes.toBytes("employees"))

// 插入数据
val put = new Put(Bytes.toBytes("3"))
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("Charlie"))
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("age"), Bytes.toBytes("35"))
table.put(put)

// 查询数据
val result = table.get(new Get(Bytes.toBytes("3")))
println(s"Name: ${Bytes.toString(result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")))}")
println(s"Age: ${Bytes.toString(result.getValue(Bytes.toBytes("info"), Bytes.toBytes("age")))}")

// 关闭连接
table.close()
connection.close()
}
}

 

运行步骤:
将上述代码保存为HBaseExample.scala。
使用SBT打包项目:

sbt package
运行程序:

java -cp target/scala-2.13/hbaseexample_2.13-0.1.jar HBaseExample
观察输出结果。

通过Scala与HBase的结合,可以实现高效的数据读写操作。HBase的列存储特性使得它在处理大规模稀疏数据时表现出色。

posted @ 2025-02-11 20:43  伐木工熊大  阅读(15)  评论(0)    收藏  举报