本文介绍如何通过Spark访问HBase增强版集群。
前提条件
注意事项
如果您想要通过公网访问,在执行文本操作前,需要将HBase社区版客户端更换为阿里云HBase客户端。具体操作,请参见升级HBase Java SDK。
如果应用部署在ECS实例,通过专有网络访问HBase增强版集群前,需要确保HBase增强版集群和ECS实例满足以下条件,以保证网络的连通性。
所在地域相同,并建议所在可用区相同(以减少网络延时)。
ECS实例与HBase增强版集群属于同一专有网络。
添加HBase增强版访问配置
方式一:通过配置文件添加访问配置。
在配置文件
hbase-site.xml
中增加下列配置项:<configuration> <!-- 集群的Java API连接地址,在控制台页面的数据库连接界面获取 --> <property> <name>hbase.zookeeper.quorum</name> <value>ld-bp150tns0sjxs****-proxy-hbaseue.hbaseue.rds.aliyuncs.com:30020</value> </property> </configuration>
方式二:通过代码在Configuration中添加参数。
// 新建一个Configuration Configuration conf = HBaseConfiguration.create(); // 集群的Java API连接地址,在控制台页面的数据库连接界面获取 conf.set("hbase.zookeeper.quorum", "ld-bp150tns0sjxs****-proxy-hbaseue.hbaseue.rds.aliyuncs.com:30020");
Spark访问示例
test(" test the spark sql count result") {
//1. 添加HBaseue访问配置
var conf = HBaseConfiguration.create
conf.set("hbase.zookeeper.quorum", "ld-bp150tns0sjxs****-proxy-hbaseue.hbaseue.rds.aliyuncs.com:30020")
//2. 创建表
val hbaseTableName = "testTable"
val cf = "f"
val column1 = cf + ":a"
val column2 = cf + ":b"
var rowsCount: Int = -1
var namespace = "spark_test"
val admin = ConnectionFactory.createConnection(conf).getAdmin()
val tableName = TableName.valueOf(namespace, hbaseTableName)
val htd = new HTableDescriptor(tableName)
htd.addFamily(new HColumnDescriptor(cf))
admin.createTable(htd)
//3. 插入测试数据
val rng = new Random()
val k: Array[Byte] = new Array[Byte](3)
val famAndQf = KeyValue.parseColumn(Bytes.toBytes(column))
val puts = new util.ArrayList[Put]()
var i = 0
for (b1 <- ('a' to 'z')) {
for (b2 <- ('a' to 'z')) {
for (b3 <- ('a' to 'z')) {
if(i < 10) {
k(0) = b1.toByte
k(1) = b2.toByte
k(2) = b3.toByte
val put = new Put(k)
put.addColumn(famAndQf(0), famAndQf(1), ("value_" + b1 + b2 + b3).getBytes())
puts.add(put)
i = i + 1
}
}
}
}
val conn = ConnectionFactory.createConnection(conf)
val table = conn.getTable(tableName)
table.put(puts)
//4. 创建spark表
val sparkTableName = "spark_hbase"
val createCmd = s"""CREATE TABLE ${sparkTableName} USING org.apache.hadoop.hbase.spark
| OPTIONS ('catalog'=
| '{"table":{"namespace":"$${hbaseTableName}", "name":"${hbaseTableName}"},"rowkey":"rowkey",
| "columns":{
| "col0":{"cf":"rowkey", "col":"rowkey", "type":"string"},
| "col1":{"cf":"cf1", "col":"a", "type":"string"},
| "col2":{"cf":"cf1", "col":"b", "type":"String"}}}'
| )""".stripMargin
println(" createCmd: \n" + createCmd + " rows : " + rowsCount)
sparkSession.sql(createCmd)
//5. 执行count sql
val result = sparkSession.sql("select count(*) from " + sparkTableName)
val sparkCounts = result.collect().apply(0).getLong(0)
println(" sparkCounts : " + sparkCounts)
文档内容是否对您有帮助?