kafka到hbase API

QQ圖片20200511215405.png

import java.util

import com.ybq.consumer.myutils.{ConnectionInstance, HbaseUtil, PropertiesUtil}
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
import org.apache.hadoop.hbase.client.{Connection, HTable, Put}
import org.apache.hadoop.hbase.util.Bytes

object HbaseDao {

private val sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
private val sdf2 = new SimpleDateFormat("yyyyMMddHHmmss")
private val cacheList = new util.ArrayList[Put]
//默認讀取resource 下面的文件hbase-site.xml
var conf: Configuration = HBaseConfiguration.create()
private var regions: Integer = Integer.valueOf(PropertiesUtil.getProperty("hbase.calllog.regions"))
private var namespace: String = PropertiesUtil.getProperty("hbase.calllog.namespace")
private var tableName: String = PropertiesUtil.getProperty("hbase.calllog.tablename")
var table: HTable = null
//首先創(chuàng)建命名空間
if(!HbaseUtil.isExisTable(conf,tableName)){
HbaseUtil.initNamespace(conf,namespace)
HbaseUtil.createTable(conf,tableName,regions,"f1","f2")
}
def put(value:String): Unit ={
if(cacheList.size() == 0){
val connection: Connection = ConnectionInstance.getConnection(conf)
table = connection.getTable(TableName.valueOf(tableName)).asInstanceOf[HTable]
table.setAutoFlush(false)
table.setWriteBufferSize(210241024)
}
val splitOri: Array[String] = value.split(",")
val caller: String = splitOri(0)
val callerName: String = splitOri(1)
val callee: String = splitOri(2)
val calleeName: String = splitOri(3)
val buildTime: String = splitOri(4)
val duration: String = splitOri(5)
val flag: String = splitOri(6)
//獲取region編碼
val regionCode: String = HbaseUtil.getRegionCode(caller, buildTime, regions)
//建立通話時長
val buildTimeReplace: String = sdf2.format(sdf1.parse(buildTime))
val buildTimeTs: String = String.valueOf(sdf1.parse(buildTime).getTime)
//生成rowKey
val rowKey: String = HbaseUtil.getRotKey(regionCode, caller, buildTimeReplace, callee, flag, duration)
//向表中插入數(shù)據(jù)
val put = new Put(Bytes.toBytes(rowKey))
//主叫號碼
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("call1"), Bytes.toBytes(caller))
//主號名稱
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("call1_name"), Bytes.toBytes(callerName))
//被叫號碼
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("call2"), Bytes.toBytes(callee))
//被叫名稱
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("call2_name"), Bytes.toBytes(calleeName))
//通話日期
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("build_time"), Bytes.toBytes(buildTime))
//通話時間
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("build_time_ts"), Bytes.toBytes(buildTimeTs))
//通過標識
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("flag"), Bytes.toBytes("1"))
//通話時長
put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("duration"), Bytes.toBytes(duration))
cacheList.add(put)

if(cacheList.size() >= 0){
  table.put(cacheList)
  table.flushCommits()
  println("插入數(shù)據(jù)成功")
  cacheList.clear()
}

}

}

object KafkaToHbase {

def main(args: Array[String]): Unit = {

//創(chuàng)建kafka消費者對象
val kafkaConsumer = new KafkaConsumer[String, String](PropertiesUtil.properties)
//訂閱指定的topic 用于數(shù)據(jù)的消費
kafkaConsumer.subscribe(util.Arrays.asList(PropertiesUtil.getProperty("kafka.topics")))
println("等待消費數(shù)據(jù)")
while (true){
  //每0.1s從指定topic中消費數(shù)據(jù)
  val records: ConsumerRecords[String, String] = kafkaConsumer.poll(100)
  //這個scala和java集合類型之間的轉(zhuǎn)換
  for(cr <- records){
    //得到每條數(shù)據(jù)的value
    val str: String = cr.value()
    println(str)
    HbaseDao.put(str)
  }
}

}

}

object ConnectionInstance {

private var connection: Connection = null

def getConnection(conf:Configuration):Connection={
if(connection == null || connection.isClosed){
connection = ConnectionFactory.createConnection(conf)
}
connection
}

}

object HbaseUtil {
def getRotKey(regionCode: String, caller: String, buildTime: String, callee: String, flag: String, duration: String): String = {
val sb = new StringBuilder
sb.append(regionCode + "")
.append(caller + "
")
.append(buildTime + "")
.append(caller + "
")
.append(flag + "_")
.append(duration)
sb.toString()
}

def getRegionCode(caller: String, buildTime: String, regions: Integer): String = {
//電話號碼長度
val len: Int = caller.length
//取出后4位號碼
val lastPhone: String = caller.substring(len - 4)
//取出建立通過時間的年月2018-02-02
val ym: String = buildTime.replaceAll("-", "")
.replaceAll(":","")
.replaceAll(" ","")
.substring(0,6)
//離散化操作 1 ^ 這個符號是異或運算 對應(yīng)位置相同為0 不同就為1
val x:Integer = Integer.valueOf(lastPhone) ^ Integer.valueOf(ym)
//離散操作
val y: Int = x.hashCode()
//生成分區(qū)號
val regionCode:Int = y % regions
//格式化分區(qū)號
val df = new DecimalFormat("00")

df.format(regionCode)

}

def createTable(conf: Configuration, tableName: String, regions: Integer, columnFamily:String*) ={
val connection: Connection = ConnectionFactory.createConnection(conf)
val admin: Admin = connection.getAdmin
val nameName = new HTableDescriptor(TableName.valueOf(tableName))
for (elem <- columnFamily) {
nameName.addFamily(new HColumnDescriptor(elem))
}
admin.createTable(nameName,getSplitKeys(regions))
}

def getSplitKeys(regions: Integer): Array[Array[Byte]] = {
//定義一個存放區(qū)間的數(shù)組
val keys = new ArrayString
//目前推算region的個數(shù)不會超過兩位數(shù) 格式化區(qū)間
val df = new DecimalFormat("00")
//對region個數(shù)進行遍歷
for(i<-0 until regions){
//使用|拼接一下
keys(i) = df.format(i) + "|"
}
//定義一個二維數(shù)組
val splitKeys = new ArrayArray[Byte]
//比較器 升序排序
val treeset = new util.TreeSetArray[Byte]
for(i<-0 until regions){
//使用|拼接一下
treeset.add(Bytes.toBytes(keys(i)))
}

val spiltKeysIterator: util.Iterator[Array[Byte]] = treeset.iterator()
var index = 0
while (spiltKeysIterator.hasNext) {
  val b: Array[Byte] = spiltKeysIterator.next()
  splitKeys(index) = b
  index = index +1
}
splitKeys

}

def initNamespace(conf: Configuration, namespace: String) = {
//獲取hbase連接
val connection: Connection = ConnectionFactory.createConnection(conf)
val admin: Admin = connection.getAdmin
val nd: NamespaceDescriptor = NamespaceDescriptor.create(namespace).addConfiguration("CREATE_TIME", String.valueOf(System.currentTimeMillis()))
.addConfiguration("AUTHOR", "yang").build()
admin.createNamespace(nd)
admin.close()
connection.close()
}

def isExisTable(conf:Configuration,tableName:String): Boolean ={
val connection: Connection = ConnectionFactory.createConnection(conf)
val admin: Admin = connection.getAdmin
val result: Boolean = admin.tableExists(TableName.valueOf(tableName))
admin.close()
connection.close()
result
}

}

object PropertiesUtil {

val is: InputStream = ClassLoader.getSystemResourceAsStream("hbase_consumer.properties")
val properties = new Properties
properties.load(is)

def getProperty(key:String):String={
val str: String = properties.getProperty(key)
str
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蛙婴,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子富玷,更是在濱河造成了極大的恐慌扭倾,老刑警劉巖攻旦,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件画株,死亡現(xiàn)場離奇詭異钝腺,居然都是意外死亡,警方通過查閱死者的電腦和手機耘成,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門榔昔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人瘪菌,你說我怎么就攤上這事撒会。” “怎么了师妙?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵诵肛,是天一觀的道長。 經(jīng)常有香客問我默穴,道長曾掂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任壁顶,我火速辦了婚禮,結(jié)果婚禮上溜歪,老公的妹妹穿的比我還像新娘若专。我一直安慰自己,他們只是感情好蝴猪,可當(dāng)我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布调衰。 她就那樣靜靜地躺著,像睡著了一般自阱。 火紅的嫁衣襯著肌膚如雪嚎莉。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天沛豌,我揣著相機與錄音趋箩,去河邊找鬼。 笑死加派,一個胖子當(dāng)著我的面吹牛叫确,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播芍锦,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼竹勉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了娄琉?” 一聲冷哼從身側(cè)響起次乓,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吓歇,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后票腰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體城看,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年丧慈,在試婚紗的時候發(fā)現(xiàn)自己被綠了析命。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡逃默,死狀恐怖鹃愤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情完域,我是刑警寧澤软吐,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站吟税,受9級特大地震影響凹耙,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜肠仪,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一肖抱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧异旧,春花似錦意述、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至潮针,卻和暖如春术荤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背每篷。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工瓣戚, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人雳攘。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓带兜,卻偏偏與公主長得像,于是被迫代替她去往敵國和親吨灭。 傳聞我的和親對象是個殘疾皇子刚照,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,442評論 2 359