一、HBase索引案例(使用redis存储索引)
在这里是简单模拟将索引存到redis中,再通过先查询索引再将Hbase中的数据查询出来。
需要考虑的问题:
1、建立redis的连接,建立Hbase的连接
2、如何创建索引,即创建索引的key和value的设计
3、如何通过将查到的索引,去查询到对应Hbase的数据
添加依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.2.3</version>
</dependency>
启动redis服务
nohup redis-server ./redis.conf &
代码编写
package com.shujia.hbaseapi.redis2hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ha.HAAdmin;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import redis.clients.jedis.Jedis;
import java.io.IOException;
import java.util.Scanner;
import java.util.Set;
public class Demo {
public static void main(String[] args) throws Exception {
//建立与hbase的连接
Configuration conf = new Configuration();
conf.set("hbase.zookeeper.quorum", "master:2181,node1:2181,node2:2181");
HConnection conn = HConnectionManager.createConnection(conf);
HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
//建立与redis的连接
Jedis jedis = new Jedis("master", 7000);
System.out.println("与hbase建立连接成功:" + conn);
System.out.println("与redis建立连接成功:" + jedis);
Scanner sc = new Scanner(System.in);
System.out.print("请输入要查询的性别:(男/女):");
String gender = sc.next();
System.out.println();
if("男".equals(gender) || "女".equals(gender)){
System.out.println("性别为 " + gender + " 的学生信息如下:");
//先去redis中把对应性别的学号取出来
Set<String> set = jedis.smembers("student_gender:" + gender);
for (String id : set) {
try {
//拿着学号去hbase中查询
HTableInterface students2 = conn.getTable("students2");
Get get = new Get(id.getBytes());
Result rs = students2.get(get);
if (rs != null) {
String ids = Bytes.toString(rs.getRow());
String name = Bytes.toString(rs.getValue("info".getBytes(), "name".getBytes()));
String age = Bytes.toString(rs.getValue("info".getBytes(), "age".getBytes()));
String gender2 = Bytes.toString(rs.getValue("info".getBytes(), "gender".getBytes()));
String clazz = Bytes.toString(rs.getValue("info".getBytes(), "clazz".getBytes()));
System.out.println("学号:" + ids + ",姓名:" + name + ",年龄:" + age + ",性别:" + gender2 + ",班级:" + clazz);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
System.out.println("性别输入有误!!");
}
}
}