提出需求
目前 hbase 服务器较少,只有 3 台服务器,要求将 电信公司的通话详单 均衡 的保存到这 3 台服务器中
提出设计方案
解决
预分区
建表时指定 分 3 个区,起止rowkey:
-001001-002002-
rowkey 设计:
- 拼装字符串:
138888_139888_20220101093000 - 对
138888_139888_20220101093000取hashcode,返回数字 - 将 hashcode 数字 对
3取模,因为现在只有3台 region server - 对取模结果前面补0,预计未来会用几百台 region server,所以要保证取模结果是
3位的 - 拼装rowkey:
3位取模结果_138888_139888_20220101093000
建表
hbase shell 环境执行:
create 'call_log2','info',SPLITS => ['001','002']
指定其实rowkey
web查看分区
start key 和 end key:
-001
001-002
002-
java代码
package top.malaoshi;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.MD5Hash;
import java.io.IOException;
public class TestRowKey {
private Connection conn;
/**
* 创建hbase连接
* @throws IOException
*/
public void conn() throws IOException {
//创建hbase配置对象
Configuration conf= HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "hadoop1,hadoop2,hadoop3");// zookeeper地址
conf.set("hbase.zookeeper.property.clientPort", "2181");// zookeeper端口
//通过配置对象创建连接
conn = ConnectionFactory.createConnection(conf);
}
public void testRowkey2() throws IOException {
//获取table对象
Table table = conn.getTable(TableName.valueOf("call_log2"));
int serverNum=3;//有3台region server
int prefixLen=3;//前缀长度,预计未来有上百台服务器,所以前缀长度是3
String tel="13900000001";
for(int d=20211001;d<20211004;d++) {// 日期:20211001-20211004
for (long i = 13800000001l; i < 13800000080l; i++) {//拨打的电话号
String base = tel + "_" +d;
int num=base.hashCode()%serverNum;//有3台region server,所以对3取模
String numStr=String.format("%0"+prefixLen+"d",num);//不足前缀长度,补0
String rowkey = numStr + "_" + base+"_132530"+"_"+i;//132530表示时间,这里为了演示,时间相同
System.out.println(rowkey);
Put put = new Put(Bytes.toBytes(rowkey));
put.addColumn(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("李雷"));
//执行put命令
table.put(put);
}
}
//关闭table
table.close();
}
public void close() throws IOException {
conn.close();
}
public static void main(String[] args) {
TestRowKey trk=new TestRowKey();
try {
trk.conn();
trk.testRowkey2();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
trk.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
web查看
参考:
https://cloud.tencent.com/developer/article/1525569


