1 需求分析
- 今天到现在为止实战课程的访问量,Spaark Streaming 把统计结果存到数据库
RDBMS(关系型数据库):MySQL, Oracle
day course_id click_count
20181218 1 30
20181218 2 10
下一个批次数据进来后,20171218 + 1 =》 click_count + 下一次的统计结果
NoSQL: HBase,Redis
HBase (一个API 就可以实现):下一个批次数据进来后,20171218 + 1 =》 click_count + 下一次的统计结果
2 具体实现
2.1 启动环境
启动 Hadoop,Zookeeper,Hbase
[hadoop@node1 ~]$ start-dfs.sh
[hadoop@node1 ~]$ zkServer.sh start
[hadoop@node1 ~]$ start-hbase.sh
[hadoop@node1 ~]$ jps
1601 NameNode
1924 SecondaryNameNode
2469 HRegionServer
2296 HMaster
1737 DataNode
2077 QuorumPeerMain
2829 Jps
2.2 创建 hbase 表
[hadoop@node1 ~]$ hbase shell
2.2.1 HBase 工具类的开发
package streamingproject.utils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.IOException;
/*
* HBase 操作工具类: Java 工具类建议采用单例模式封装
* */
public class HBaseUtils {
HBaseAdmin admin = null;
Configuration configuration = null;
/*
*
* */
private HBaseUtils() {
configuration = new Configuration();
configuration.set("hbase.zookeeper.quorum", "node1:2181");
configuration.set("hbase.rootdir", "hdfs://node1:8020/hbase");
try {
admin = new HBaseAdmin(configuration);
} catch (IOException e) {
e.printStackTrace();
}
}
private static HBaseUtils instance = null;
public static synchronized HBaseUtils getInstance() {
if (null == instance) {
instance = new HBaseUtils();
}
return instance;
}
//根据表名获取 HTable 的实例
public HTable getTable(String tableName) {
HTable table = null;
try {
table = new HTable(configuration, tableName);
} catch (IOException e) {
e.printStackTrace();
}
return table;
}
/**
* @param tableName HBase表名
* @param rowkey
* @param cf HBase的 columnfamily
* @param column
* @param value
* @Description:添加一条记录到 HBase 表
* @return: void
**/
public void put(String tableName, String rowkey, String cf, String column, String value) {
HTable table = getTable(tableName);
Put put = new Put(Bytes.toBytes(rowkey));
put.add(Bytes.toBytes(cf), Bytes.toBytes(column), Bytes.toBytes(value));
try {
table.put(put);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// HTable table = HBaseUtils.getInstance().getTable("course_clickcount");
// System.out.println(table.getName().getNameAsString());
String tableName = "course_clickcount";
String rowkey = "20181111_88";
String cf = "info";
String column = "click_count";
String value = "2";
HBaseUtils.getInstance().put(tableName,rowkey,cf,column,value);
}
}